﻿using ABDLight.Components;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace ABDLight
{
    public partial class frmLoad : Form
    {
        //public static readonly ILog log = LogManager.GetLogger(typeof(frmLoad));
        int GlobStartPos = 0;
        int GlobEndPos = 0;
        public static int RecordCountInFile = 0;
        System.Data.OleDb.OleDbConnection cnn = new OleDbConnection();
        public frmLoad()
        {
            //log.Info("== Инициализация формы frmLoad ==");
            InitializeComponent();
            this.cmbSeparator.SelectedIndex = 0;
            this.cmbType.SelectedIndex = 2;
            this.cmbCode.SelectedIndex = 0;
            inputType_Name.DisplayIndex = 2;
            this.ClientSize = new System.Drawing.Size(SystemInformation.PrimaryMonitorSize.Width / 2, SystemInformation.PrimaryMonitorSize.Height / 4 * 3);

            //SQLiteData.DBCreate();
            //this.Width = ;
            //this.Height -= 1000; 
        }

        public string CheckType = "none";
        public bool AddrMatch = false;
        public bool EmailMatch = false;
        public bool PhoneMatch = false;
        public bool FioMatch_1 = false;
        public bool FioMatch_2 = false;
        public bool OrgDublMatch = false;
        public bool choose_addrmatch = false;

        public Dictionary<string, string> CleanResult = new  Dictionary<string, string>();
        public DataTable CleanResultDT;


        public bool isFileLoad = false;

        public class FileSettings
        {
            public string FilePath { get; set; }
            public string FileName { get; set; }
            public string FullFilePath { get; set; }
            public string FileEncoding { get; set; }
            public string FileSeparator { get; set; }
            public string File_chFC { get; set; }
            public string File_chKov { get; set; }

            public string FileType { get; set; }

            public string Status_job { get; set; }


            public string UserID { get; set; }
            public string DB { get; set; }
            public string Table { get; set; }
            public string Server { get; set; }
            public string start_period { get; set; }

            public  FileSettings()
            {
                FilePath  = "";
                FileName  = "";
                FullFilePath = FilePath + "\\" + FileName;
                FileEncoding  = "";
                FileSeparator  = "";
                File_chFC  = "";
                File_chKov  = "";
                FileType = "";
                Status_job = "";

                UserID = ABDLight.Properties.Settings.Default.UserID;
                DB = "";
                Table = "";
                Server = "";
                start_period = "";

            }

            public static FileSettings GetFileSettings(string FilePath = "",string FileName =  "settings.ini")
            {
                if (string.IsNullOrEmpty(FilePath))
                {
                    FilePath = Application.StartupPath;
                }
                FileSettings fs = new FileSettings();
                aejw.cIni oIni = new aejw.cIni(FilePath + "\\" + FileName);
                fs.FilePath = oIni.ReadValue("FileSettings", "FilePath", ABDLight.Properties.Settings.Default.DefFilePath);
                fs.FileName = oIni.ReadValue("FileSettings", "FileName", ABDLight.Properties.Settings.Default.CleanFileName);
                fs.FullFilePath = oIni.ReadValue("FileSettings", "FullFilePath", fs.FilePath + "\\" + fs.FileName);
                fs.FileEncoding = oIni.ReadValue("FileSettings", "FileEncoding", "windows - 1251");
                fs.FileSeparator = oIni.ReadValue("FileSettings", "FileSeparator", ";");
                fs.File_chFC = oIni.ReadValue("FileSettings", "File_chFC", "True");
                fs.File_chKov = oIni.ReadValue("FileSettings", "File_chKov", "False");
                fs.FileType = oIni.ReadValue("FileSettings", "File_FileType", "False");
                
                fs.Status_job = oIni.ReadValue("FileSettings", "Status_job", "0");
                fs.UserID = oIni.ReadValue("FileSettings", "UserID", ABDLight.Properties.Settings.Default.UserID);
                fs.DB = oIni.ReadValue("FileSettings", "DB", ABDLight.Properties.Settings.Default.DB);
                fs.Table = oIni.ReadValue("FileSettings", "Table", ABDLight.Properties.Settings.Default.Table);
                fs.Server = oIni.ReadValue("FileSettings", "Server", ABDLight.Properties.Settings.Default.Server);
                fs.start_period = oIni.ReadValue("FileSettings", "start_period", DateTime.Now.ToString("yyyy:MM:dd_HH:mm:ss:fff"));

                return fs;

            }

            public static void SetFileSettings(FileSettings fs = null,string FilePath = "")
            {
                if (fs == null)
                {
                    return;
                }
             
                if (string.IsNullOrEmpty(FilePath))
                {
                    FilePath = Application.StartupPath;
                }

                aejw.cIni oIni = new aejw.cIni(FilePath + "\\settings.ini");
                oIni.WriteValue("FileSettings", "FilePath", fs.FilePath);
                oIni.WriteValue("FileSettings", "FileName", fs.FileName);

                oIni.WriteValue("FileSettings", "FullFilePath", fs.FullFilePath);
                oIni.WriteValue("FileSettings", "FileEncoding", fs.FileEncoding);
                oIni.WriteValue("FileSettings", "FileSeparator", fs.FileSeparator);
                oIni.WriteValue("FileSettings", "File_chFC", fs.File_chFC);
                oIni.WriteValue("FileSettings", "File_chKov", fs.File_chKov);
                oIni.WriteValue("FileSettings", "File_FileType", fs.FileType);
                oIni.WriteValue("FileSettings", "Status_job", fs.Status_job);

 
                oIni.WriteValue("FileSettings", "UserID", fs.UserID);
                oIni.WriteValue("FileSettings", "DB", fs.DB);
                oIni.WriteValue("FileSettings", "Table", fs.Table);
                oIni.WriteValue("FileSettings", "Server", fs.Server);
                oIni.WriteValue("FileSettings", "start_period", fs.start_period);

            }
        }
            

        private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbSeparator.Visible = (cmbType.SelectedIndex == 0)? true : false;
            lbSeparator.Visible = (cmbType.SelectedIndex == 0) ? true : false;
            chFC.Visible = (cmbType.SelectedIndex <= 2) ? true : false;
            lbCode.Visible = (cmbType.SelectedIndex == 0) ? true : false;
            cmbCode.Visible = (cmbType.SelectedIndex == 0) ? true : false;
            chKov.Visible = (cmbType.SelectedIndex == 0) ? true : false;


            frmClean.cCfg.LastFileIndex = cmbType.SelectedIndex ;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFile();
        }
        private void OpenFile(){
            switch (cmbType.SelectedIndex)
            {
                case 0:
                    FolderBrowserDialog dlg = new FolderBrowserDialog();
                    dlg.SelectedPath= ((frmMine)this.Owner).cfg.TmpDir;

                    if (dlg.ShowDialog() == DialogResult.OK) {

                        edFile.Text = dlg.SelectedPath;
                        DirectoryInfo dir = new DirectoryInfo(edFile.Text);
                        cmbTbl.Items.Clear();
                        foreach (FileInfo files in dir.GetFiles())
                        {
                            if (files.Name.ToLower().IndexOf(".txt") > -1 || files.Name.ToLower().IndexOf(".csv") > -1)
                            {
                                cmbTbl.Items.Add(files.Name);
                                cmbTbl.SelectedIndex = 0;
                                
                            }
                        } 
                    }
     
                    btnClean.Enabled = false;
                    btnClean.FlatStyle = System.Windows.Forms.FlatStyle.Popup;

                    return;  
           
                
                case 1:
                    openFileDialog1.Filter = "Excel 2000 files (*.xls)|*.xls";
                    break;
                case 2:
                    openFileDialog1.Filter = "Excel 2007 files (*.xlsx)|*.xlsx";
                    break;
                case 3:
                    openFileDialog1.Filter = "Access 2000 files (*.mdb)|*.mdb";
                    break;
                case 4:
                    openFileDialog1.Filter = "Access 2007 files (*.accdb)|*.accdb";
                    break;

            }
           
            openFileDialog1.ShowDialog();
            OpenConn();

            btnClean.Enabled = false;
            btnClean.FlatStyle = System.Windows.Forms.FlatStyle.Popup;

        }

        private void AutoOpenFile()
        {
            aejw.cIni oIni = new aejw.cIni(frmClean.cCfg.AppPath + "\\settings.ini");
            string LastFilePath = oIni.ReadValue("LastSettings", "LastFilePath", Application.StartupPath);
            string LastFileName = oIni.ReadValue("LastSettings", "LastFileName", "");
            string LastFileIndex = oIni.ReadValue("LastSettings", "LastFileIndex", "");

            if (!string.IsNullOrEmpty(LastFileIndex) && Convert.ToInt32(LastFileIndex) != -1)
                cmbType.SelectedIndex = Convert.ToInt32(LastFileIndex);
            
             FileSettings _FileSettings = new FileSettings();
             _FileSettings = FileSettings.GetFileSettings(Application.StartupPath);


             if (this.cmbType.SelectedIndex == 0 && File.Exists(_FileSettings.FilePath + "/" + _FileSettings.FileName))
            {
                edFile.Text = _FileSettings.FilePath;
                cmbTbl.SelectedValue = _FileSettings.FileName;
                cmbSeparator.SelectedValue = _FileSettings.FileSeparator;
                bool tmp_chFC = true; bool tmp_chKov = true;
                if (bool.TryParse(_FileSettings.File_chFC, out tmp_chFC)) chFC.Checked = tmp_chFC;
                if (bool.TryParse(_FileSettings.File_chKov, out tmp_chKov)) chKov.Checked = tmp_chKov;
                cmbType.SelectedValue = _FileSettings.FileType;
            }

             if (this.cmbType.SelectedIndex == 2 && File.Exists(_FileSettings.FilePath))
             {
                 edFile.Text = _FileSettings.FilePath;
                 cmbTbl.SelectedValue = _FileSettings.FileName;
                 cmbSeparator.SelectedValue = _FileSettings.FileSeparator;
                 bool tmp_chFC = true; bool tmp_chKov = true;
                 if (bool.TryParse(_FileSettings.File_chFC, out tmp_chFC)) chFC.Checked = tmp_chFC;
                 if (bool.TryParse(_FileSettings.File_chKov, out tmp_chKov)) chKov.Checked = tmp_chKov;
                 cmbType.SelectedValue = _FileSettings.FileType;
             }



            switch (cmbType.SelectedIndex)
            {

                case 0:
                    if (!string.IsNullOrEmpty(LastFilePath))
                    {
                        edFile.Text = LastFilePath;
                    
                        DirectoryInfo dir = new DirectoryInfo(edFile.Text);
                        cmbTbl.Items.Clear();
                        
                        foreach (FileInfo files in dir.GetFiles())
                        {
                            if (files.Name.ToLower().IndexOf(".txt") > -1 || files.Name.ToLower().IndexOf(".csv") > -1)
                            {
                                cmbTbl.Items.Add(files.Name);
                                cmbTbl.SelectedIndex = 0;

                            }
                        }

                    }
                    else
                    {
                        MessageBox.Show("Ошибка чтения файла!!!", "Внимание");
                        //log.Error("Ошибка чтения файла!!!");
                        return;
                    }

                    return;


                case 1:
                    openFileDialog1.Filter = "Excel 2000 files (*.xls)|*.xls";
                    break;
                case 2:
                    openFileDialog1.Filter = "Excel 2007 files (*.xlsx)|*.xlsx";
                    break;
                case 3:
                    openFileDialog1.Filter = "Access 2000 files (*.mdb)|*.mdb";
                    break;
                case 4:
                    openFileDialog1.Filter = "Access 2007 files (*.accdb)|*.accdb";
                    break;

            }

          /*
            if (!string.IsNullOrEmpty(LastFileName))
            {
                edFile.Text = LastFileName.Trim();
            }
            openFileDialog1.ShowDialog();*/
            OpenConn();

        }



        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            frmClean.cCfg.LastFileName = openFileDialog1.FileName;
            edFile.Text = openFileDialog1.FileName.Trim();
        }


        public void StrReadTest1(string filename = "file.txt", string StringLine = "", char[] CharArr = null, int type = 2)
        {
            
            string line = StringLine;


            if (type == 0)
            {
                // Creates new StringReader instance from System.IO
                using (StringReader reader = new StringReader(StringLine))
                {
                    // Loop over the lines in the string.
                    int count = 0;
                    line = StringLine;
                    while ((line = reader.ReadLine()) != null)
                    {
                        count++;
                        Console.WriteLine("Line {0}: {1}", count, line);
                    }
                }

            }

            if (type == 1)
            {
                using (StreamReader reader1 = new StreamReader(filename))
                {
                    line = reader1.ReadLine();
                }
                Console.WriteLine(line);
            }

            if (type == 2)
            {
                StreamReader reader2 = new StreamReader(filename);
                while (true)
                {
                    line = reader2.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    Console.WriteLine(line); // Use line.
                }

            }
        }



        public void btnLoad_Click(object sender, EventArgs e)
        {

            if (edFile.Text == "" || cmbTbl.Text == "")
            {
                MessageBox.Show("Выберите файл для чистки!", "Внимание",
                                                  MessageBoxButtons.OK,
                                                  MessageBoxIcon.Warning);
                return;
            }




            DataTable DTtemp = new DataTable(); 
            grdColumn.Rows.Clear();
            ((frmMine)this.Owner).dtMain.Clear();
            ((frmMine)this.Owner).dtVariant.Clear();
            ((frmMine)this.Owner).dtMain.Columns.Clear();
            ((frmMine)this.Owner).dtVariant.Columns.Clear();

            ((frmMine)this.Owner).dtMain.Reset();
            ((frmMine)this.Owner).dtVariant.Reset();

            frmClean.cCfg.ErrorRowIndex = -1;
            frmClean.cCfg.isPause = false;

            aejw.cIni oIni = new aejw.cIni(Application.StartupPath + "\\settings.ini");

            bool FileExists = false;
            bool isNewFile = false;
             FileExists = File.Exists(edFile.Text + "\\" + cmbTbl.Text);

            FileSettings _FileSettings = new FileSettings();
            _FileSettings = FileSettings.GetFileSettings(Application.StartupPath);


            _FileSettings.FileName = cmbTbl.Text;
            _FileSettings.FilePath = edFile.Text;
            _FileSettings.FileEncoding = cmbCode.Text;
            _FileSettings.FileSeparator = cmbSeparator.Text;
            _FileSettings.File_chFC = chFC.Checked.ToString().ToLower();
            _FileSettings.File_chKov = chKov.Checked.ToString().ToLower();
            _FileSettings.FileType = cmbType.Text;
            FileSettings.SetFileSettings(_FileSettings, Application.StartupPath);




            try
            {
                /*
                if (((frmMine)this.Owner).dtMain.Columns["ID_IQ"] == null)
                {
                    DataColumn ID_IQ = new DataColumn();
                    ID_IQ.ColumnName = "ID_IQ";
                    ID_IQ.DataType = System.Type.GetType("System.Int32");
                    ((frmMine)this.Owner).dtMain.Columns.Add(ID_IQ);

                    ID_IQ.SetOrdinal(0);
                }
                if (((frmMine)this.Owner).dtMain.Columns["ID_IQ"] != null)
                {
                    for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                    {
                        ((frmMine)this.Owner).dtMain.Rows[ind]["ID_IQ"] = ind + 1;
                    }
                }
                */
                if (cmbType.SelectedIndex == 0)
                {
                    
                    //((frmMine)this.Owner).dtMain.Clear();
                    frmClean.cCfg.chKov = chKov.Checked;

                    //((frmMine)this.Owner).OpenTextFile(edFile.Text + "/" + cmbTbl.Text, ((frmMine)this.Owner).dtMain, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, true);


                    if (((frmMine)this.Owner).cfg.isUseDB.ToLower() == "true")
                    {
                        int tmpMaxRowsToRead = 100;
                        if (sender != null)
                        {
                            Hashtable pars = new Hashtable();
                            pars.Add("isPreview","true");
                   
                            pars.Add("MaxRowsToRead", tmpMaxRowsToRead);
                            pars.Add("isCreate", "false");
                            frmProgress.frm = new frmProgress();
                            frmProgress.frm.Owner = this;
                            frmProgress.frm.ExecuteCommand("OpenTextFileToDB", pars);
                            
                        }
                        else
                        {
                            Hashtable pars = new Hashtable();
                            pars.Add("isPreview", "false");
                            int.TryParse(ABDLight.Properties.Settings.Default.MaxRowsToRead, out tmpMaxRowsToRead);
                            pars.Add("MaxRowsToRead", tmpMaxRowsToRead);
                            pars.Add("isCreate", "false");
                            frmProgress.frm = new frmProgress();
                            frmProgress.frm.Owner = this;
                            frmProgress.frm.ExecuteCommand("OpenTextFileToDB", pars);
                        }

                           

                        if (isNewFile)
                        {
                            Dictionary<String, String> data = new Dictionary<string, string>();
                            data.Add("c_FileName", _FileSettings.FileName);
                            data.Add("c_FilePath", _FileSettings.FilePath);
                            data.Add("c_FullFilePath", _FileSettings.FullFilePath);
                            data.Add("c_start_period", DateTime.Now.ToString("yyyy:MM:dd_HH:mm:ss:fff"));
                            data.Add("c_FileEncoding", _FileSettings.FileEncoding);
                            data.Add("c_FileSeparator", _FileSettings.FileSeparator);
                            data.Add("c_chFC", _FileSettings.File_chFC);
                            data.Add("c_chKov", _FileSettings.File_chKov);
                            data.Add("c_FileType", _FileSettings.FileType);


                            data.Add("c_UserID", ABDLight.Properties.Settings.Default.UserID);
                            data.Add("c_DB", ABDLight.Properties.Settings.Default.DB);
                            data.Add("c_Table", ABDLight.Properties.Settings.Default.Table);
                            data.Add("c_Server", ABDLight.Properties.Settings.Default.Server);

                           
                            CleanBackUp.Insert(ABDLight.Properties.Settings.Default.ABDLightDBConnectionString, ABDLight.Properties.Settings.Default.DB, "t_user_cleaning_jobs", data);
                        }
                       
                    }
                    else
                    {
                        if (sender != null)
                        {

                            ((frmMine)this.Owner).OpenTextFile(edFile.Text + "/" + cmbTbl.Text, ((frmMine)this.Owner).dtMain, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, true);
                        }
                        else
                        {
                            ((frmMine)this.Owner).OpenTextFile(edFile.Text + "/" + cmbTbl.Text, ((frmMine)this.Owner).dtMain, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, false);
                        }

                        if (isNewFile)
                        {
                            Dictionary<String, String> data = new Dictionary<string, string>();
                            data.Add("c_FileName", _FileSettings.FileName);
                            data.Add("c_FilePath", _FileSettings.FilePath);
                            data.Add("c_FullFilePath", _FileSettings.FullFilePath);
                            data.Add("c_start_period", DateTime.Now.ToString("yyyy:MM:dd_HH:mm:ss:fff"));
                            data.Add("c_FileEncoding", _FileSettings.FileEncoding);
                            data.Add("c_FileSeparator", _FileSettings.FileSeparator);
                            data.Add("c_chFC", _FileSettings.File_chFC);
                            data.Add("c_chKov", _FileSettings.File_chKov);
                            data.Add("c_FileType", _FileSettings.FileType);


                            data.Add("c_UserID", ABDLight.Properties.Settings.Default.UserID);
                            data.Add("c_DB", ABDLight.Properties.Settings.Default.DB);
                            data.Add("c_Table", ABDLight.Properties.Settings.Default.Table);
                            data.Add("c_Server", ABDLight.Properties.Settings.Default.Server);


                        }
                    }                 
                }
                else
                {
                    //if (cnn.State == ConnectionState.Closed) cnn.Open();

                    if (cmbTbl.Text == "") {
                        if (grdColumn.SelectedRows.Count == 0)
                        {

                            MessageBox.Show("Не выбрано ни одного файла!", "Внимание",
                                               MessageBoxButtons.OK,
                                               MessageBoxIcon.Warning);

                            return;
                        }
                    
                    }



                    DataColumn ID_IQ = new DataColumn();
                    ID_IQ.ColumnName = "ID_IQ";
                    ID_IQ.DataType = System.Type.GetType("System.Int32");
                    ((frmMine)this.Owner).dtMain.Columns.Add(ID_IQ);

                    if (((frmMine)this.Owner).dtMain.Columns["ID_IQ"] != null)
                    {
                        for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                        {
                            ((frmMine)this.Owner).dtMain.Rows[ind]["ID_IQ"] = ind + 1;
                        }
                    }
                    //начитываем все сразу
                    //OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + cmbTbl.Text + "]", cnn);                                    
                    //da.Fill(((frmMine)this.Owner).dtMain);                 
                    //cnn.Close();

                  
                        int tmpMaxRowsToRead = 100;
                        if (sender != null)
                        {
                            Hashtable pars = new Hashtable();
                            pars.Add("isPreview", "true");

                            pars.Add("MaxRowsToRead", tmpMaxRowsToRead);
                            pars.Add("isCreate", "false");
                            frmProgress.frm = new frmProgress();
                            frmProgress.frm.Owner = this;
                            frmProgress.frm.ExecuteCommand("OpenTextFileToDB", pars);

                        }
                        else
                        {
                            Hashtable pars = new Hashtable();
                            pars.Add("isPreview", "false");
                            int.TryParse(ABDLight.Properties.Settings.Default.MaxRowsToRead, out tmpMaxRowsToRead);
                            pars.Add("MaxRowsToRead", tmpMaxRowsToRead);
                            pars.Add("isCreate", "false");
                            frmProgress.frm = new frmProgress();
                            frmProgress.frm.Owner = this;
                            frmProgress.frm.ExecuteCommand("OpenTextFileToDB", pars);
                        }


                    /*
                    if (cmbType.SelectedIndex == 1)
                        ((frmMine)this.Owner).dtMain = ExcelFunctions.ReadFile(edFile.Text, cmbTbl.Text, chFC.Checked, "XLS");
                    if (cmbType.SelectedIndex == 2)
                        ((frmMine)this.Owner).dtMain = ExcelFunctions.ReadFile(edFile.Text, cmbTbl.Text, chFC.Checked, "XLSX");
                    */

                    _FileSettings = new FileSettings();
                    _FileSettings = FileSettings.GetFileSettings(Application.StartupPath);
                    _FileSettings.FileName = cmbTbl.Text;
                    _FileSettings.FilePath = edFile.Text;
                    _FileSettings.FileEncoding = cmbCode.Text;
                    _FileSettings.FileSeparator = cmbSeparator.Text;
                    _FileSettings.File_chFC = chFC.Checked.ToString().ToLower();
                    _FileSettings.File_chKov = chKov.Checked.ToString().ToLower();
                    _FileSettings.FileType = cmbType.Text;
                    FileSettings.SetFileSettings(_FileSettings, Application.StartupPath);
                }

                if (((frmMine)this.Owner).dtMain.Columns["ID_IQ"] == null)
                {
                    DataColumn ID_IQ = new DataColumn();
                    ID_IQ.ColumnName = "ID_IQ";
                    ID_IQ.DataType = System.Type.GetType("System.Int32");
                    ((frmMine)this.Owner).dtMain.Columns.Add(ID_IQ);

                    ID_IQ.SetOrdinal(0);
                }
                if (((frmMine)this.Owner).dtMain.Columns["ID_IQ"] != null)
                {
                    for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                    {
                        ((frmMine)this.Owner).dtMain.Rows[ind]["ID_IQ"] = ind + 1;
                    }
                }

                pr_Grid1.LoadGrig(((frmMine)this.Owner).dtMain);
                pr_Grid1.Refresh();
//////////////////                
                for (int i = 1; i < ((frmMine)this.Owner).dtMain.Columns.Count; i += 1)
                {
                    grdColumn.Rows.Add(1);

                    grdColumn.Rows[i - 1].Cells[0].Value = ((frmMine)this.Owner).dtMain.Columns[i].ColumnName;

                    string ColumnType = "Не обрабатывать";
                    

                    ColumnType = oIni.ReadValue("LoadedCollumns", ((frmMine)this.Owner).dtMain.Columns[i].ColumnName, ColumnType);
                   
                    switch (ColumnType)
                    {
                        case "Не обрабатывать":
                            grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[0];
                            grdColumn.CurrentRow.Cells["IsAddr"].Value = false;
                            grdColumn.Rows[i - 1].Cells["IsAddr"].Value = false;
                            ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.White;
                 
                           
                            break;
                        case "Адрес (в одном поле)":
                            grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[1];
                            grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true;
                            ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
                            oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                            frmClean.cCfg.CheckType = "addrmatch"; 
                            break;
                        //case "Тип Адреса":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[2];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Страна":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[3];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Тип региона":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[4];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Регион":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[5];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Тип района":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[6];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Район":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[7];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Тип города":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[8];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Город":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[9];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Тип НП":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[10];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "НП":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[11];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Тип улицы":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[12];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Улица":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[13];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Тип дома":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[14];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;                           
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Дом":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[15];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Корпус":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[16];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Строение":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[17];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Литера":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[18];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Тип квартиры":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[19];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Квартира":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[20];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "Индекс":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[21];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); 
                        //    frmClean.cCfg.CheckType = "addrmatch";
                        //    break; 
                        //case "КЛАДР":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[22];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break; 
                        //case "ОКАТО":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[23];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break; 
                        //case "ОКТМО":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[24];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break; 
                        //case "Дом с квартирой":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[25];
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break; 
                        case "E-mail":
                            grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[2];
                            grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true;                           
                            grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
                            oIni.WriteValue("CheckType", "NowCheck", "emailmatch");
                            frmClean.cCfg.CheckType = "emailmatch";
                            break; 
                        //case "ФИО (в одном поле)":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[27];
                        //    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
                        //    oIni.WriteValue("CheckType", "NowCheck", "fiomatch_1");
                        //    frmClean.cCfg.CheckType = "fiomatch_1";
                        //    break;                       
                        //case "Отчество":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[28];
                        //    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2");
                        //    frmClean.cCfg.CheckType = "fiomatch_2";
                        //    break;
                        //case "Имя":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[29];
                        //    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2");
                        //    frmClean.cCfg.CheckType = "fiomatch_2";
                        //    break;
                        //case "Фамилия":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[30];
                        //    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2");
                        //    frmClean.cCfg.CheckType = "fiomatch_2";
                        //    break;
                        //case "Телефон":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[31];
                        //    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; 
                        //    oIni.WriteValue("CheckType", "NowCheck", "phonematch");
                        //    frmClean.cCfg.CheckType = "phonematch";
                        //    break;
                        //case "Организация":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[32];
                        //    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
                        //    oIni.WriteValue("CheckType", "NowCheck", "orgdublmatch");
                        //    frmClean.cCfg.CheckType = "orgdublmatch";
                        //    break;
                        //case "Адрес (Для выбора)":
                        //    grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[33];
                        //    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        //    grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
                        //    oIni.WriteValue("CheckType", "NowCheck", "choose_addrmatch");
                        //    frmClean.cCfg.CheckType = "choose_addrmatch";
                        //    break;
                            
                            
                    }
                }

                //lbCount.Text = "Всего загружено: " + ((frmMine)this.Owner).dtMain.Rows.Count.ToString() + " записей из " + System.IO.File.ReadAllLines(edFile.Text + "/" + cmbTbl.Text).Length.ToString();
                lbCount.Text = "Всего загружено: " + ((frmMine)this.Owner).dtMain.Rows.Count.ToString() + " записей из " + RecordCountInFile.ToString();

                   btnClean.Enabled = true;
                   btnClean.FlatStyle = System.Windows.Forms.FlatStyle.Standard;


            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Внимание",
                                              MessageBoxButtons.OK,
                                              MessageBoxIcon.Error);
                return;
            }

            pr_Grid1.Grid_RowPrePaint(null, null);
        }

        private void OpenConn()
        {
            cmbTbl.Items.Clear();
            var fs = new FileStream(edFile.Text, FileMode.Open, FileAccess.Read);

            if (cmbType.SelectedIndex == 1)
            { 
                HSSFWorkbook wb = new HSSFWorkbook(fs);
                for (int i = 0; i < wb.Count; i++)
                {
                    cmbTbl.Items.Add(wb.GetSheetAt(i).SheetName);
                }
            }
            if (cmbType.SelectedIndex == 2)
            {
                XSSFWorkbook wb = new XSSFWorkbook(fs);
                for (int i = 0; i < wb.Count; i++)
                {
                    cmbTbl.Items.Add(wb.GetSheetAt(i).SheetName);
                }
            }
            cmbTbl.SelectedIndex = 0;



           }

    private DataColumn CloneColumn(DataColumn col)
    {
        DataColumn _col=new DataColumn();
        _col.ColumnName = col.ColumnName;
        _col.Caption = col.Caption;
        _col.DataType = col.DataType;
        return _col;
    }

    private void btnClean_Click(object sender, EventArgs e)
    {
        btnLoad_Click(null, null);

        ABDLight.Properties.Settings.Default.isLoadFromDB = false;
        ABDLight.Properties.Settings.Default.CleanFileName = edFile.Text + "\\" + cmbTbl.Text;
        if (cmbType.SelectedIndex == 0)
            ABDLight.Properties.Settings.Default.CleanTableName = cmbTbl.Text;
        else
            ABDLight.Properties.Settings.Default.CleanTableName = edFile.Text.Substring(edFile.Text.LastIndexOf("\\") + 1, edFile.Text.Length - 1 - edFile.Text.LastIndexOf("\\"));

        aejw.cIni oIni = new aejw.cIni(frmClean.cCfg.AppPath + "\\settings.ini");
        CheckType = oIni.ReadValue("CheckType", "NowCheck", CheckType);
        frmClean.cCfg.CheckType = CheckType;

        //Проверяем на наличие в БД
        if (!SQLiteData.CheckFile(ABDLight.Properties.Settings.Default.CleanFileName))
        { 
            if (MessageBox.Show("Этот файл уже был загружен для чистки!" +
                             "\nПри повторной загрузке результаты предыдущей чистки будут удалены!" +
                             "\nЧтобы продолжить, нажмите 'OK'." +
                             "\nЧтобы вернуться к чистке старого файла, нажмите 'Отмена' и выберете в главном меню пункт Функционал => Загрузка сохраннёного файла."
                      , "Внимание", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
            {
                this.Close();
                return;
            }
        }

        if (string.IsNullOrEmpty(CheckType) || CheckType == "none")
        {
            MessageBox.Show("Не выбрано ни одно поле для чистки!\nПовторите выбор типа полей!", "Внимание",
                                              MessageBoxButtons.OK,
                                              MessageBoxIcon.Warning);
            return;
        }
            else if (CheckType == "addrmatch")
            {
                AddrMatch = true;
            }
            else if (CheckType == "emailmatch")
            {
                EmailMatch = true;
            }
            else if (CheckType == "fiomatch_1")
            {
                FioMatch_1 = true;
            }
            else if (CheckType == "fiomatch_2")
            {
                FioMatch_2 = true;
            }
            else if (CheckType == "phonematch")
            {
                PhoneMatch = true;
            }
            else if (CheckType == "orgdublmatch")
            {
                OrgDublMatch = true;
            }
            else if (CheckType == "choose_addrmatch")
            {
                choose_addrmatch = true;
            }

        /*
        foreach (DataGridViewRow Row in grdColumn.Rows)
        {
            
        }
        */
        if (!AddrMatch && !EmailMatch && !FioMatch_1 && !FioMatch_2 && !PhoneMatch && !OrgDublMatch && !choose_addrmatch)
        {
            MessageBox.Show("Вы не указали столбец (поле) для разбора!", "Внимание",
                                              MessageBoxButtons.OK,
                                              MessageBoxIcon.Warning);
            return;
        }

        //Проверка: надо ли переначитать файл или сразу загрузить из базы.
        //переначитка
        //if (sender != null)
        //{
        //    btnLoad_Click(null, null);
        //}
        //else 
        ////начитка и базы
        //if (sender == null)
        //{
        //    Hashtable pars = new Hashtable();
        //    pars.Add("DB_Name", ABDLight.Properties.Settings.Default.DB);
        //    ExecuteCommand("OpenFromDB", pars);
        //}


        //ABDLight.Properties.Settings.Default.SQLiteTab = cmbTbl.Text;
        //ABDLight.Properties.Settings.Default.Save();


       if(cmbType.SelectedIndex > 0)
           ((frmMine)this.Owner).cfg.fileName = (cmbTbl.Text.IndexOf("#") > -1) ? cmbTbl.Text.Substring(0, cmbTbl.Text.IndexOf("#")) : cmbTbl.Text;
       else
           ((frmMine)this.Owner).cfg.fileName = (cmbTbl.Text.IndexOf(".") > -1) ? cmbTbl.Text.Substring(0, cmbTbl.Text.IndexOf(".")) : cmbTbl.Text;

       if (cmbTbl.SelectedValue != null)
       {
           ((frmMine)this.Owner).cfg.CleanFileName = cmbTbl.SelectedText;
           ABDLight.Properties.Settings.Default.CleanFileName = ((frmMine)this.Owner).cfg.CleanFileName;
           ABDLight.Properties.Settings.Default.Save();
       }

        pr_Grid1.Grid.DataSource = null;
        if (grdColumn.RowCount == 0) return;



        if (AddrMatch && CheckType == "addrmatch" && sender != null)
        {

            DataColumn iqCheck = new DataColumn();
            iqCheck.ColumnName = "isCheck";
            iqCheck.Caption = "Прочищен";
            iqCheck.DataType = System.Type.GetType("System.Boolean");

            ((frmMine)this.Owner).dtMain.Columns.Add(iqCheck);
            iqCheck.SetOrdinal(1);

            DataColumn isChanget = new DataColumn();
            isChanget.ColumnName = "isChanget";
            isChanget.Caption = "Ручной разбор";
            isChanget.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isChanget);
            isChanget.SetOrdinal(2);

            DataColumn isBad = new DataColumn();
            isBad.ColumnName = "isBad";
            isBad.Caption = "Плохой";
            isBad.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isBad);
            isBad.SetOrdinal(3);

            DataColumn textStatus = new DataColumn();
            textStatus.ColumnName = "textStatus";
            textStatus.Caption = "Статус Разбора";
            textStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(textStatus);
            textStatus.SetOrdinal(4);

            //DataColumn iqSetRow = new DataColumn();
            //iqSetRow.ColumnName = "Выбрать";
            //iqSetRow.DataType = System.Type.GetType("System.Boolean");
            //((frmMine)this.Owner).dtVariant.Columns.Add(iqSetRow);


            //DataColumn iqParentID = new DataColumn();
            //iqParentID.ColumnName = "iqParentID";
            //iqParentID.DataType = System.Type.GetType("System.Int32");
            //((frmMine)this.Owner).dtVariant.Columns.Add(iqParentID);



            DataColumn iqWorkAddress = new DataColumn();
            iqWorkAddress.ColumnName = "iqWorkAddress";
            iqWorkAddress.Caption = "Полный разобранный адрес";
            iqWorkAddress.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqWorkAddress);

            //

            //
            DataColumn iqPostCodeIn = new DataColumn();
            iqPostCodeIn.ColumnName = "iqPostCodeIn";
            iqPostCodeIn.Caption = "Индекс исходного адреса";
            iqPostCodeIn.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPostCodeIn);

            DataColumn iqPostCode = new DataColumn();
            iqPostCode.ColumnName = "iqPostCode";
            iqPostCode.Caption = "Индекс разобранного адреса";
            iqPostCode.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPostCode);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqPostCode));

            DataColumn iqFullAddress = new DataColumn();
            iqFullAddress.ColumnName = "iqFullAddress";
            iqFullAddress.Caption = "Разобранный адрес";
            iqFullAddress.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqFullAddress);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqFullAddress));



            DataColumn iqHouse = new DataColumn();
            iqHouse.ColumnName = "iqHouse";
            iqHouse.Caption = "Дом";
            iqHouse.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqHouse);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqHouse));

            DataColumn iqCase = new DataColumn();
            iqCase.ColumnName = "iqCase";
            iqCase.Caption = "Корпус";
            iqCase.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCase);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCase));

            DataColumn iqBuild = new DataColumn();
            iqBuild.ColumnName = "iqBuild";
            iqBuild.Caption = "Строение";
            iqBuild.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqBuild);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqBuild));

            DataColumn iqLiter = new DataColumn();
            iqLiter.ColumnName = "iqLiter";
            iqLiter.Caption = "Литера";
            iqLiter.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqLiter);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqLiter));

            DataColumn iqVlad = new DataColumn();
            iqVlad.ColumnName = "iqVlad";
            iqVlad.Caption = "Владение";
            iqVlad.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqVlad);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqVlad));

            DataColumn iqBlock = new DataColumn();
            iqBlock.ColumnName = "iqBlock";
            iqBlock.Caption = "Блок";
            iqBlock.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqBlock);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqBlock));

            DataColumn iqPom = new DataColumn();
            iqPom.ColumnName = "iqPom";
            iqPom.Caption = "Помещение";
            iqPom.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPom);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqPom));

            DataColumn iqPav = new DataColumn();
            iqPav.ColumnName = "iqPav";
            iqPav.Caption = "Павильон";
            iqPav.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPav);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqPav));

            DataColumn iqUch = new DataColumn();
            iqUch.ColumnName = "iqUch";
            iqUch.Caption = "Участок";
            iqUch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqUch);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqUch));

            DataColumn iqObsch = new DataColumn();
            iqObsch.ColumnName = "iqObsch";
            iqObsch.Caption = "Общежитие";
            iqObsch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqObsch);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqObsch));

            DataColumn iqFlat = new DataColumn();
            iqFlat.ColumnName = "iqFlat";
            iqFlat.Caption = "Квартира";
            iqFlat.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqFlat);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqFlat));
            //////////////////////////////////////////////////
            DataColumn iqKom = new DataColumn();
            iqKom.ColumnName = "iqKom";
            iqKom.Caption = "Комната";
            iqKom.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqKom);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqKom));

            DataColumn iqOffice = new DataColumn();
            iqOffice.ColumnName = "iqOffice";
            iqOffice.Caption = "Офис";
            iqOffice.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqOffice);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqOffice));

            DataColumn iqKab = new DataColumn();
            iqKab.ColumnName = "iqKab";
            iqKab.Caption = "Кабинет";
            iqKab.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqKab);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqKab));

            DataColumn iqAbon = new DataColumn();
            iqAbon.ColumnName = "iqAbon";
            iqAbon.Caption = "а/я";
            iqAbon.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqAbon);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqAbon));

            DataColumn iqVch = new DataColumn();
            iqVch.ColumnName = "iqVch";
            iqVch.Caption = "в/ч";
            iqVch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqVch);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqVch));

            DataColumn iqComment = new DataColumn();
            iqComment.ColumnName = "iqComment";
            iqComment.Caption = "Комментарий";
            iqComment.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqComment);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqComment));


            DataColumn iqKLADR = new DataColumn();
            iqKLADR.ColumnName = "iqKLADR";
            iqKLADR.Caption = "КЛАДР";
            iqKLADR.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqKLADR);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqKLADR));

            DataColumn iqLostAddr = new DataColumn();
            iqLostAddr.ColumnName = "iqLostAddr";
            iqLostAddr.Caption = "Не разобрано";
            iqLostAddr.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqLostAddr);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqLostAddr));


            DataColumn iqError = new DataColumn();
            iqError.ColumnName = "iqError";
            iqError.Caption = "Ошибка";
            iqError.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqError);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqError));

            DataColumn iqStatus = new DataColumn();
            iqStatus.ColumnName = "iqStatus";
            iqStatus.Caption = "Статус";
            iqStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqStatus);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqStatus));


            DataColumn iqCountry = new DataColumn();
            iqCountry.ColumnName = "iqCountry";
            iqCountry.Caption = "Страна";
            iqCountry.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCountry);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCountry));

            DataColumn iqRegion = new DataColumn();
            iqRegion.ColumnName = "iqRegion";
            iqRegion.Caption = "Регион";
            iqRegion.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqRegion);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqRegion));

            DataColumn iqRegionType = new DataColumn();
            iqRegionType.ColumnName = "iqRegionType";
            iqRegionType.Caption = "Тип региона";
            iqRegionType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqRegionType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqRegionType));

            DataColumn iqSubRegion = new DataColumn();
            iqSubRegion.ColumnName = "iqSubRegion";
            iqSubRegion.Caption = "Район";
            iqSubRegion.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqSubRegion);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqSubRegion));

            DataColumn iqSubRegionType = new DataColumn();
            iqSubRegionType.ColumnName = "iqSubRegionType";
            iqSubRegionType.Caption = "Тип района";
            iqSubRegionType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqSubRegionType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqSubRegionType));

            DataColumn iqCity = new DataColumn();
            iqCity.ColumnName = "iqCity";
            iqCity.Caption = "Город";
            iqCity.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCity);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCity));

            DataColumn iqCityType = new DataColumn();
            iqCityType.ColumnName = "iqCityType";
            iqCityType.Caption = "Тип города";
            iqCityType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCityType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCityType));


            DataColumn iqNp = new DataColumn();
            iqNp.ColumnName = "iqNp";
            iqNp.Caption = "НП";
            iqNp.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqNp);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqNp));

            DataColumn iqNpType = new DataColumn();
            iqNpType.ColumnName = "iqNpType";
            iqNpType.Caption = "Тип НП";
            iqNpType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqNpType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqNpType));


            DataColumn iqStreet = new DataColumn();
            iqStreet.ColumnName = "iqStreet";
            iqStreet.Caption = "Улица";
            iqStreet.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqStreet);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqStreet));

            DataColumn iqStreetType = new DataColumn();
            iqStreetType.ColumnName = "iqStreetType";
            iqStreetType.Caption = "Тип улицы";
            iqStreetType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqStreetType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqStreetType));


            if (((frmMine)this.Owner).cfg.isUseDB.ToLower() == "true")
            {
                //((frmMine)this.Owner).dtMain.Clear();
                //((frmMine)this.Owner).OpenTextFileToDB(edFile.Text + "/" + cmbTbl.Text, DTtemp, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, 10);
                //((frmMine)this.Owner).dtMain = CleanBackUp.GetDataTable(ABDLight.Properties.Settings.Default.ABDLightDBConnectionString, ABDLight.Properties.Settings.Default.InitialCatalog, ABDLight.Properties.Settings.Default.Table);
                //((frmMine)this.Owner).OpenTextFile(edFile.Text + "/" + cmbTbl.Text, ((frmMine)this.Owner).dtMain, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, true);
                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                {
                    for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                    {
                        if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                        {
                            if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                            {
                                ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                                //frmClean.cCfg.StartInd = grdColumn.CurrentCell.OwningRow.Index + 2;
                            }
                            //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                        }
                    }

                }
            }
            else
            {
                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                {
                    for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                    {
                        if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                        {
                            if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                            {
                                ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                                frmClean.cCfg.StartInd = grdColumn[0, i].RowIndex + 5;
                            }
                            //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                        }
                    }

                }
            }

            frmClean.cCfg.ErrorRowIndex = -1;
            frmClean.cCfg.nAll = 0;
            frmClean.cCfg.nBad = 0;
            frmClean.cCfg.nSomn = 0;
            frmClean.cCfg.nGood = 0;



            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();
        }
        else if (AddrMatch && CheckType == "addrmatch" && sender == null)
        {

          


            if (((frmMine)this.Owner).cfg.isUseDB.ToLower() == "true")
            {
                //((frmMine)this.Owner).dtMain.Clear();
                //((frmMine)this.Owner).OpenTextFileToDB(edFile.Text + "/" + cmbTbl.Text, DTtemp, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, 10);
                //((frmMine)this.Owner).dtMain = CleanBackUp.GetDataTable(ABDLight.Properties.Settings.Default.ABDLightDBConnectionString, ABDLight.Properties.Settings.Default.InitialCatalog, ABDLight.Properties.Settings.Default.Table);
                //((frmMine)this.Owner).OpenTextFile(edFile.Text + "/" + cmbTbl.Text, ((frmMine)this.Owner).dtMain, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, true);
            
            }
            else
            {
                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                {
                    for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                    {
                        if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                        {
                            if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                            {
                                ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                                frmClean.cCfg.StartInd = grdColumn[0, i].RowIndex + 5;
                            
                            }
                            //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                        }
                    }

                }
            }

            frmClean.cCfg.ErrorRowIndex = -1;
            frmClean.cCfg.nAll = 0;
            frmClean.cCfg.nBad = 0;
            frmClean.cCfg.nSomn = 0;
            frmClean.cCfg.nGood = 0;
            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();
        }
        else if (choose_addrmatch && CheckType == "choose_addrmatch" && sender != null)
        {
            /*
            if (sender != null)
            {

                btnLoad_Click(null, null);
            }
            else if (sender == null)
            {
                btnLoad_Click("not_null", null);
                ((frmMine)this.Owner).dtMain = CleanBackUp.GetDataTable(ABDLight.Properties.Settings.Default.ABDLightDBConnectionString, ABDLight.Properties.Settings.Default.InitialCatalog, "CleanResult");

            }
             * */
            DataColumn iqCheck = new DataColumn();
            iqCheck.ColumnName = "isCheck";
            iqCheck.Caption = "Прочищен";
            iqCheck.DataType = System.Type.GetType("System.Boolean");

            ((frmMine)this.Owner).dtMain.Columns.Add(iqCheck);
            iqCheck.SetOrdinal(1);

            DataColumn isChanget = new DataColumn();
            isChanget.ColumnName = "isChanget";
            isChanget.Caption = "Редактирован";
            isChanget.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isChanget);
            isChanget.SetOrdinal(2);

            DataColumn isBad = new DataColumn();
            isBad.ColumnName = "isBad";
            isBad.Caption = "Плохой";
            isBad.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isBad);
            isBad.SetOrdinal(3);

            DataColumn textStatus = new DataColumn();
            textStatus.ColumnName = "textStatus";
            textStatus.Caption = "Статус Разбора";
            textStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(textStatus);
            textStatus.SetOrdinal(4);

            //DataColumn iqSetRow = new DataColumn();
            //iqSetRow.ColumnName = "Выбрать";
            //iqSetRow.DataType = System.Type.GetType("System.Boolean");
            //((frmMine)this.Owner).dtVariant.Columns.Add(iqSetRow);


            //DataColumn iqParentID = new DataColumn();
            //iqParentID.ColumnName = "iqParentID";
            //iqParentID.DataType = System.Type.GetType("System.Int32");
            //((frmMine)this.Owner).dtVariant.Columns.Add(iqParentID);



            DataColumn iqWorkAddress = new DataColumn();
            iqWorkAddress.ColumnName = "iqWorkAddress";
            iqWorkAddress.Caption = "Исходный адрес";
            iqWorkAddress.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqWorkAddress);

            //

            //
            DataColumn iqPostCodeIn = new DataColumn();
            iqPostCodeIn.ColumnName = "iqPostCodeIn";
            iqPostCodeIn.Caption = "Вх.Индекс";
            iqPostCodeIn.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPostCodeIn);

            DataColumn iqPostCode = new DataColumn();
            iqPostCode.ColumnName = "iqPostCode";
            iqPostCode.Caption = "Индекс";
            iqPostCode.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPostCode);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqPostCode));

            DataColumn iqFullAddress = new DataColumn();
            iqFullAddress.ColumnName = "iqFullAddress";
            iqFullAddress.Caption = "Разобранная часть адреса";
            iqFullAddress.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqFullAddress);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqFullAddress));



            DataColumn iqHouse = new DataColumn();
            iqHouse.ColumnName = "iqHouse";
            iqHouse.Caption = "Дом";
            iqHouse.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqHouse);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqHouse));

            DataColumn iqCase = new DataColumn();
            iqCase.ColumnName = "iqCase";
            iqCase.Caption = "Корпус";
            iqCase.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCase);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCase));

            DataColumn iqBuild = new DataColumn();
            iqBuild.ColumnName = "iqBuild";
            iqBuild.Caption = "Строение";
            iqBuild.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqBuild);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqBuild));

            DataColumn iqLiter = new DataColumn();
            iqLiter.ColumnName = "iqLiter";
            iqLiter.Caption = "Литера";
            iqLiter.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqLiter);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqLiter));

            DataColumn iqVlad = new DataColumn();
            iqVlad.ColumnName = "iqVlad";
            iqVlad.Caption = "Владение";
            iqVlad.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqVlad);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqVlad));

            DataColumn iqBlock = new DataColumn();
            iqBlock.ColumnName = "iqBlock";
            iqBlock.Caption = "Блок";
            iqBlock.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqBlock);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqBlock));

            DataColumn iqPom = new DataColumn();
            iqPom.ColumnName = "iqPom";
            iqPom.Caption = "Помещение";
            iqPom.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPom);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqPom));

            DataColumn iqPav = new DataColumn();
            iqPav.ColumnName = "iqPav";
            iqPav.Caption = "Павильон";
            iqPav.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqPav);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqPav));

            DataColumn iqUch = new DataColumn();
            iqUch.ColumnName = "iqUch";
            iqUch.Caption = "Участок";
            iqUch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqUch);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqUch));

            DataColumn iqObsch = new DataColumn();
            iqObsch.ColumnName = "iqObsch";
            iqObsch.Caption = "Общежитие";
            iqObsch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqObsch);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqObsch));

            DataColumn iqFlat = new DataColumn();
            iqFlat.ColumnName = "iqFlat";
            iqFlat.Caption = "Квартира";
            iqFlat.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqFlat);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqFlat));
            //////////////////////////////////////////////////
            DataColumn iqKom = new DataColumn();
            iqKom.ColumnName = "iqKom";
            iqKom.Caption = "Комната";
            iqKom.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqKom);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqKom));

            DataColumn iqOffice = new DataColumn();
            iqOffice.ColumnName = "iqOffice";
            iqOffice.Caption = "Офис";
            iqOffice.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqOffice);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqOffice));

            DataColumn iqKab = new DataColumn();
            iqKab.ColumnName = "iqKab";
            iqKab.Caption = "Кабинет";
            iqKab.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqKab);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqKab));

            DataColumn iqAbon = new DataColumn();
            iqAbon.ColumnName = "iqAbon";
            iqAbon.Caption = "а/я";
            iqAbon.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqAbon);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqAbon));

            DataColumn iqVch = new DataColumn();
            iqVch.ColumnName = "iqVch";
            iqVch.Caption = "в/ч";
            iqVch.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqVch);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqVch));

            DataColumn iqComment = new DataColumn();
            iqComment.ColumnName = "iqComment";
            iqComment.Caption = "Комментарий";
            iqComment.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqComment);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqComment));


            DataColumn iqKLADR = new DataColumn();
            iqKLADR.ColumnName = "iqKLADR";
            iqKLADR.Caption = "КЛАДР";
            iqKLADR.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqKLADR);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqKLADR));

            DataColumn iqLostAddr = new DataColumn();
            iqLostAddr.ColumnName = "iqLostAddr";
            iqLostAddr.Caption = "Не разобрано";
            iqLostAddr.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqLostAddr);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqLostAddr));


            DataColumn iqError = new DataColumn();
            iqError.ColumnName = "iqError";
            iqError.Caption = "Ошибка";
            iqError.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqError);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqError));

            DataColumn iqStatus = new DataColumn();
            iqStatus.ColumnName = "iqStatus";
            iqStatus.Caption = "Статус";
            iqStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqStatus);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqStatus));


            DataColumn iqCountry = new DataColumn();
            iqCountry.ColumnName = "iqCountry";
            iqCountry.Caption = "Страна";
            iqCountry.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCountry);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCountry));

            DataColumn iqRegion = new DataColumn();
            iqRegion.ColumnName = "iqRegion";
            iqRegion.Caption = "Регион";
            iqRegion.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqRegion);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqRegion));

            DataColumn iqRegionType = new DataColumn();
            iqRegionType.ColumnName = "iqRegionType";
            iqRegionType.Caption = "Тип региона";
            iqRegionType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqRegionType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqRegionType));

            DataColumn iqSubRegion = new DataColumn();
            iqSubRegion.ColumnName = "iqSubRegion";
            iqSubRegion.Caption = "Район";
            iqSubRegion.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqSubRegion);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqSubRegion));

            DataColumn iqSubRegionType = new DataColumn();
            iqSubRegionType.ColumnName = "iqSubRegionType";
            iqSubRegionType.Caption = "Тип района";
            iqSubRegionType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqSubRegionType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqSubRegionType));

            DataColumn iqCity = new DataColumn();
            iqCity.ColumnName = "iqCity";
            iqCity.Caption = "Город";
            iqCity.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCity);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCity));

            DataColumn iqCityType = new DataColumn();
            iqCityType.ColumnName = "iqCityType";
            iqCityType.Caption = "Тип города";
            iqCityType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqCityType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqCityType));


            DataColumn iqNp = new DataColumn();
            iqNp.ColumnName = "iqNp";
            iqNp.Caption = "НП";
            iqNp.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqNp);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqNp));

            DataColumn iqNpType = new DataColumn();
            iqNpType.ColumnName = "iqNpType";
            iqNpType.Caption = "Тип НП";
            iqNpType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqNpType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqNpType));


            DataColumn iqStreet = new DataColumn();
            iqStreet.ColumnName = "iqStreet";
            iqStreet.Caption = "Улица";
            iqStreet.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqStreet);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqStreet));

            DataColumn iqStreetType = new DataColumn();
            iqStreetType.ColumnName = "iqStreetType";
            iqStreetType.Caption = "Тип улицы";
            iqStreetType.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqStreetType);
            ((frmMine)this.Owner).dtVariant.Columns.Add(CloneColumn(iqStreetType));

            /*
            if (((frmMine)this.Owner).cfg.isUseDB.ToLower() == "true")
            {
                //((frmMine)this.Owner).dtMain.Clear();
                //((frmMine)this.Owner).OpenTextFileToDB(edFile.Text + "/" + cmbTbl.Text, DTtemp, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, 10);
                //((frmMine)this.Owner).dtMain = CleanBackUp.GetDataTable(ABDLight.Properties.Settings.Default.ABDLightDBConnectionString, ABDLight.Properties.Settings.Default.InitialCatalog, ABDLight.Properties.Settings.Default.Table);
                //((frmMine)this.Owner).OpenTextFile(edFile.Text + "/" + cmbTbl.Text, ((frmMine)this.Owner).dtMain, cmbCode.Text, cmbSeparator.Text, chFC.Checked, chKov.Checked, true);
                int imp_choose_addrmatch_num = 0;
                oIni.RemoveSection("choose_addrmatch");
                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                {
                    for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                    {
                        if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                        {
                            
                            if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                            {
                                ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                                if (ind == 0)
                                {
                                    imp_choose_addrmatch_num += 1;
                                    oIni.WriteValue("choose_addrmatch", imp_choose_addrmatch_num.ToString(), grdColumn[0, i].Value.ToString());
                                }
                            }
                            else if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (Для выбора)") >= 0)
                            {                         
                                if (ind == 0)
                                {
                                    imp_choose_addrmatch_num += 1;
                                    oIni.WriteValue("choose_addrmatch", imp_choose_addrmatch_num.ToString(), grdColumn[0, i].Value.ToString());
                                }

                            }
                            //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                        }
                    }
                    if (ind == 0)
                    {
                        
                        oIni.WriteValue("choose_addrmatch", "addrmatch_num", imp_choose_addrmatch_num.ToString());
                    }
                    
                }
                
            }
            else
            {
                int imp_choose_addrmatch_num = 0;
                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                {
                    for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                    {
                        if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                        {
                            imp_choose_addrmatch_num += 1;
                            if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                            {
                                ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                            }
                            //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                           
                        }
                    }

                }
            }
            */

            int imp_choose_addrmatch_num = 0;
            oIni.RemoveSection("choose_addrmatch");
            for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
            {
                for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                {
                    if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                    {

                        if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                        {
                            ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                            if (ind == 0)
                            {
                                imp_choose_addrmatch_num += 1;
                                oIni.WriteValue("choose_addrmatch", imp_choose_addrmatch_num.ToString(), grdColumn[0, i].Value.ToString());
                            }
                        }
                        else if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (Для выбора)") >= 0)
                        {
                            if (ind == 0)
                            {
                                imp_choose_addrmatch_num += 1;
                                oIni.WriteValue("choose_addrmatch", imp_choose_addrmatch_num.ToString(), grdColumn[0, i].Value.ToString());
                            }

                        }
                        //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                    }
                }
                if (ind == 0)
                {

                    oIni.WriteValue("choose_addrmatch", "addrmatch_num", imp_choose_addrmatch_num.ToString());
                }

            }



            frmClean.cCfg.ErrorRowIndex = -1;
            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();

            
        }
        else if (choose_addrmatch && CheckType == "choose_addrmatch" && sender == null)
        {
           

            if (((frmMine)this.Owner).cfg.isUseDB.ToLower() == "true")
            {
                for (int i = 0; i <= grdColumn.RowCount - 1; i++ )
                {

                    /*
                    switch (grdColumn[0, i].ToString())
                    {


                        case "Прочищен":
                           // col.DataType = System.Type.GetType("System.Boolean");
                             ((frmMine)this.Owner).dtMain.Columns[i].DataType =  System.Type.GetType("System.Boolean");                                                    
                            break;
                        case "isChanget":
                            ((frmMine)this.Owner).dtMain.Columns[i].DataType = System.Type.GetType("System.Boolean");  
                            break;
                        case "isBad":
                            ((frmMine)this.Owner).dtMain.Columns[i].DataType = System.Type.GetType("System.Boolean");  
                            break;
                        case "textStatus":
                           // col.Caption = "Плохой";
                           // col.Caption = "Статус Разбора";
                           // col.SetOrdinal(4);
                            break;
                    }
          */
                  

                }
               /*
                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                {
                    for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                    {
                        if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                        {

                            if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                            {

                                ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                                if (ind == 0)
                                {
                                 
                                    oIni.WriteValue("choose_addrmatch", imp_choose_addrmatch_num.ToString(), grdColumn[0, i].Value.ToString());
                                }
                            }
                            else if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (Для выбора)") >= 0)
                            {
                                if (ind == 0)
                                {
                               
                                    oIni.WriteValue("choose_addrmatch", imp_choose_addrmatch_num.ToString(), grdColumn[0, i].Value.ToString());
                                }

                            }
                            //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                        }
                    }
                    if (ind == 0)
                    {

                        oIni.WriteValue("choose_addrmatch", "addrmatch_num", imp_choose_addrmatch_num.ToString());
                    }

                }
               */
            }
            else
            {
                int imp_choose_addrmatch_num = 0;
                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
                {
                    for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                    {
                        if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                        {
                            imp_choose_addrmatch_num += 1;
                            if (grdColumn[2, i].Value.ToString().IndexOf("Адрес (в одном поле)") >= 0)
                            {
                                ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                            }
                            //((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkAddress"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";

                        }
                    }

                }
            }
            frmClean.cCfg.ErrorRowIndex = -1;
            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();


        }
        else if (EmailMatch && CheckType == "emailmatch")
        {
            DataColumn iqCheck = new DataColumn();
            iqCheck.ColumnName = "isCheck";
            iqCheck.Caption = "Прочищен";
            iqCheck.DataType = System.Type.GetType("System.Boolean");

            ((frmMine)this.Owner).dtMain.Columns.Add(iqCheck);
            iqCheck.SetOrdinal(1);

            DataColumn isChanget = new DataColumn();
            isChanget.ColumnName = "isChanget";
            isChanget.Caption = "Редактирован";
            isChanget.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isChanget);
            isChanget.SetOrdinal(2);

            DataColumn isBad = new DataColumn();
            isBad.ColumnName = "isBad";
            isBad.Caption = "Плохой";
            isBad.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isBad);
            isBad.SetOrdinal(3);

            DataColumn textStatus = new DataColumn();
            textStatus.ColumnName = "textStatus";
            textStatus.Caption = "Статус Разбора";
            textStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(textStatus);
            textStatus.SetOrdinal(4);

            //DataColumn iqParentID = new DataColumn();
            //iqParentID.ColumnName = "iqParentID";
            //iqParentID.DataType = System.Type.GetType("System.Int32");
            //((frmMine)this.Owner).dtVariant.Columns.Add(iqParentID);



            DataColumn iqWorkEmail = new DataColumn();
            iqWorkEmail.ColumnName = "iqWorkEmail";
            iqWorkEmail.Caption = "Исходный Email";
            iqWorkEmail.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqWorkEmail);

            DataColumn status_code = new DataColumn();
            status_code.ColumnName = "status_code";
            status_code.Caption = "Код результата";
            status_code.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(status_code);

            DataColumn c_message = new DataColumn();
            c_message.ColumnName = "c_message";
            c_message.Caption = "Пояснение результата";
            c_message.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(c_message);

            for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
            {
                for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                {
                    if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                    {
                        ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkEmail"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                    }
                }

            }
            frmClean.cCfg.ErrorRowIndex = -1;
            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();
            
        }
        else if (PhoneMatch && CheckType == "phonematch")
        {
            DataColumn iqCheck = new DataColumn();
            iqCheck.ColumnName = "isCheck";
            iqCheck.Caption = "Прочищен";
            iqCheck.DataType = System.Type.GetType("System.Boolean");

            ((frmMine)this.Owner).dtMain.Columns.Add(iqCheck);
            iqCheck.SetOrdinal(1);

            DataColumn isChanget = new DataColumn();
            isChanget.ColumnName = "isChanget";
            isChanget.Caption = "Редактирован";
            isChanget.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isChanget);
            isChanget.SetOrdinal(2);

            DataColumn isBad = new DataColumn();
            isBad.ColumnName = "isBad";
            isBad.Caption = "Плохой";
            isBad.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isBad);
            isBad.SetOrdinal(3);

            DataColumn textStatus = new DataColumn();
            textStatus.ColumnName = "textStatus";
            textStatus.Caption = "Статус Разбора";
            textStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(textStatus);
            textStatus.SetOrdinal(4);

            DataColumn iqParentID = new DataColumn();
            iqParentID.ColumnName = "iqParentID";
            iqParentID.DataType = System.Type.GetType("System.Int32");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqParentID);

            DataColumn iqWorkEmail = new DataColumn();
            iqWorkEmail.ColumnName = "iqWorkPhone";
            iqWorkEmail.Caption = "Исходные данные";
            iqWorkEmail.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqWorkEmail);

            DataColumn с_kladr_out = new DataColumn();
            с_kladr_out.ColumnName = "kladr_out";
            с_kladr_out.Caption = "КЛАДР";
            с_kladr_out.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(с_kladr_out);

            DataColumn с_phone_formatted = new DataColumn();
            с_phone_formatted.ColumnName = "phone_formatted";
            с_phone_formatted.Caption = "Международный Формат";
            с_phone_formatted.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(с_phone_formatted);

            DataColumn с_phone_ded = new DataColumn();
            с_phone_ded.ColumnName = "phone_ded";
            с_phone_ded.Caption = "Проверен";
            с_phone_ded.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(с_phone_ded);

            DataColumn с_valid = new DataColumn();
            с_valid.ColumnName = "valid";
            с_valid.Caption = "Результат Проверки";
            с_valid.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(с_valid);

            DataColumn с_status_desc = new DataColumn();
            с_status_desc.ColumnName = "status_desc";
            с_status_desc.Caption = "Статус Проверки";
            с_status_desc.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(с_status_desc);


            for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
            {
                for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                {
                    if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                    {
                        ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkPhone"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                    }
                }

            }


            frmClean.cCfg.ErrorRowIndex = -1;
            ((frmMine)this.Owner).OpenFrmClean();          
            this.Close();

        }
        else if (FioMatch_1 && CheckType == "fiomatch_1")
        {
            DataColumn iqCheck = new DataColumn();
            iqCheck.ColumnName = "isCheck";
            iqCheck.Caption = "Прочищен";
            iqCheck.DataType = System.Type.GetType("System.Boolean");

            ((frmMine)this.Owner).dtMain.Columns.Add(iqCheck);
            iqCheck.SetOrdinal(1);

            DataColumn isChanget = new DataColumn();
            isChanget.ColumnName = "isChanget";
            isChanget.Caption = "Редактирован";
            isChanget.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isChanget);
            isChanget.SetOrdinal(2);

            DataColumn isBad = new DataColumn();
            isBad.ColumnName = "isBad";
            isBad.Caption = "Плохой";
            isBad.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isBad);
            isBad.SetOrdinal(3);

            DataColumn textStatus = new DataColumn();
            textStatus.ColumnName = "textStatus";
            textStatus.Caption = "Статус Разбора";
            textStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(textStatus);
            textStatus.SetOrdinal(4);

            DataColumn iqParentID = new DataColumn();
            iqParentID.ColumnName = "iqParentID";
            iqParentID.DataType = System.Type.GetType("System.Int32");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqParentID);

            DataColumn iqWorkFIO = new DataColumn();
            iqWorkFIO.ColumnName = "iqWorkFIO";
            iqWorkFIO.Caption = "Исходное ФИО";
            iqWorkFIO.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqWorkFIO);

            DataColumn lname = new DataColumn();
            lname.ColumnName = "c_lname";
            lname.Caption = "Фамилия";
            lname.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(lname);

            DataColumn fname = new DataColumn();
            fname.ColumnName = "c_fname";
            fname.Caption = "Имя";
            fname.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(fname);

            DataColumn mname = new DataColumn();
            mname.ColumnName = "c_mname";
            mname.Caption = "Отчество";
            mname.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(mname);

            DataColumn gender = new DataColumn();
            gender.ColumnName = "c_gender";
            gender.Caption = "Пол";
            gender.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(gender);

            DataColumn error = new DataColumn();
            error.ColumnName = "c_error";
            error.Caption = "Статус Проверки";
            error.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(error);

            DataColumn error_status = new DataColumn();
            error_status.ColumnName = "c_error_status";
            error_status.Caption = "Описание ошибки";
            error_status.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(error_status);
           


            for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
            {
                for (int i = grdColumn.RowCount - 1; i >= 0; i--)
                {
                    if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                    {
                        ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkFIO"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                    }
                }

            }
            frmClean.cCfg.ErrorRowIndex = -1;
            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();
        }
        else if (FioMatch_2 && CheckType == "fiomatch_2")
        {
            DataColumn iqCheck = new DataColumn();
            iqCheck.ColumnName = "isCheck";
            iqCheck.Caption = "Прочищен";
            iqCheck.DataType = System.Type.GetType("System.Boolean");

            ((frmMine)this.Owner).dtMain.Columns.Add(iqCheck);
            iqCheck.SetOrdinal(1);

            DataColumn isChanget = new DataColumn();
            isChanget.ColumnName = "isChanget";
            isChanget.Caption = "Редактирован";
            isChanget.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isChanget);
            isChanget.SetOrdinal(2);

            DataColumn isBad = new DataColumn();
            isBad.ColumnName = "isBad";
            isBad.Caption = "Плохой";
            isBad.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isBad);
            isBad.SetOrdinal(3);

            DataColumn textStatus = new DataColumn();
            textStatus.ColumnName = "textStatus";
            textStatus.Caption = "Статус Разбора";
            textStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(textStatus);
            textStatus.SetOrdinal(4);

            DataColumn iqParentID = new DataColumn();
            iqParentID.ColumnName = "iqParentID";
            iqParentID.DataType = System.Type.GetType("System.Int32");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqParentID);

            DataColumn iqWorkFIO = new DataColumn();
            iqWorkFIO.ColumnName = "iqWorkFIO";
            iqWorkFIO.Caption = "Исходное ФИО";
            iqWorkFIO.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqWorkFIO);

            DataColumn lname = new DataColumn();
            lname.ColumnName = "c_lname";
            lname.Caption = "Фамилия";
            lname.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(lname);

            DataColumn fname = new DataColumn();
            fname.ColumnName = "c_fname";
            fname.Caption = "Имя";
            fname.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(fname);

            DataColumn mname = new DataColumn();
            mname.ColumnName = "c_mname";
            mname.Caption = "Отчество";
            mname.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(mname);

            DataColumn gender = new DataColumn();
            gender.ColumnName = "c_gender";
            gender.Caption = "Пол";
            gender.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(gender);

            DataColumn error = new DataColumn();
            error.ColumnName = "c_error";
            error.Caption = "Статус Проверки";
            error.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(error);

            DataColumn error_status = new DataColumn();
            error_status.ColumnName = "c_error_status";
            error_status.Caption = "Описание ошибки";
            error_status.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(error_status);



            for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
            {
                for (int i = 0; i <= grdColumn.RowCount - 1; i++)
                {
                    if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                    {
                        ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkFIO"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                    }
                }

            }
            frmClean.cCfg.ErrorRowIndex = -1;
            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();
        }
            //////////// 
        else if (OrgDublMatch && CheckType == "orgdublmatch")
        {
            DataColumn iqCheck = new DataColumn();
            iqCheck.ColumnName = "isCheck";
            iqCheck.Caption = "Прочищен";
            iqCheck.DataType = System.Type.GetType("System.Boolean");

            ((frmMine)this.Owner).dtMain.Columns.Add(iqCheck);
            iqCheck.SetOrdinal(1);

            DataColumn isChanget = new DataColumn();
            isChanget.ColumnName = "isChanget";
            isChanget.Caption = "Редактирован";
            isChanget.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isChanget);
            isChanget.SetOrdinal(2);

            DataColumn isBad = new DataColumn();
            isBad.ColumnName = "isBad";
            isBad.Caption = "Плохой";
            isBad.DataType = System.Type.GetType("System.Boolean");
            ((frmMine)this.Owner).dtMain.Columns.Add(isBad);
            isBad.SetOrdinal(3);

            DataColumn textStatus = new DataColumn();
            textStatus.ColumnName = "textStatus";
            textStatus.Caption = "Статус Разбора";
            textStatus.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(textStatus);
            textStatus.SetOrdinal(4);

            DataColumn iqParentID = new DataColumn();
            iqParentID.ColumnName = "iqParentID";
            iqParentID.DataType = System.Type.GetType("System.Int32");
            ((frmMine)this.Owner).dtVariant.Columns.Add(iqParentID);

            DataColumn iqWorkFullName = new DataColumn();
            iqWorkFullName.ColumnName = "iqWorkFullName";
            iqWorkFullName.Caption = "Входная строка";
            iqWorkFullName.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(iqWorkFullName);

            DataColumn c_itog = new DataColumn();
            c_itog.ColumnName = "c_itog";
            c_itog.Caption = "c_itog";
            c_itog.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(c_itog);

            DataColumn c_fullname = new DataColumn();
            c_fullname.ColumnName = "c_fullname";
            c_fullname.Caption = "c_fullname";
            c_fullname.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(c_fullname);

            DataColumn c_phone = new DataColumn();
            c_phone.ColumnName = "c_phone";
            c_phone.Caption = "Телефон";
            c_phone.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(c_phone);

            DataColumn c_address = new DataColumn();
            c_address.ColumnName = "c_address";
            c_address.Caption = "Адрес";
            c_address.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(c_address);

            DataColumn c_post_code = new DataColumn();
            c_post_code.ColumnName = "c_post_code";
            c_post_code.Caption = "Индекс";
            c_post_code.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(c_post_code);

            DataColumn c_kladr = new DataColumn();
            c_kladr.ColumnName = "c_kladr";
            c_kladr.Caption = "КЛАДР";
            c_kladr.DataType = System.Type.GetType("System.String");
            ((frmMine)this.Owner).dtMain.Columns.Add(c_kladr); 

            for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
            {
                for (int i = 0; i <= grdColumn.RowCount - 1; i++)
                {
                    if (grdColumn[1, i].Value != null && (bool)grdColumn[1, i].Value == true)
                    {
                        ((frmMine)this.Owner).dtMain.Rows[ind]["iqWorkFullName"] += ((frmMine)this.Owner).dtMain.Rows[ind][grdColumn[0, i].Value.ToString()].ToString().Trim() + " ";
                    }
                }

            }
            frmClean.cCfg.ErrorRowIndex = -1;
            ((frmMine)this.Owner).OpenFrmClean();
            this.Close();
        }
        else if (OrgDublMatch && CheckType == "orgdublmatch")
        {
        }


        
    }

    private void frmLoad_Load(object sender, EventArgs e)
    {
        
        //openFileDialog1.InitialDirectory = ((frmMine)this.Owner).cfg.TmpDir;
        try
        {
            AutoOpenFile(); 
        }
        catch (Exception ex) { }
        

        FileSettings _FileSettings = new FileSettings();
        _FileSettings = FileSettings.GetFileSettings(Application.StartupPath);
        
        if (File.Exists(_FileSettings.FilePath + "/" + _FileSettings.FileName))
        {
            edFile.Text = _FileSettings.FilePath;
            int tmpNum = 0;
            foreach(var item in cmbTbl.Items)
            {

                if (item.ToString() == _FileSettings.FileName) 
                {
                  cmbTbl.SelectedIndex =  tmpNum;
                }
                tmpNum++;
            }
            tmpNum = 0;
            foreach (var item in cmbSeparator.Items)
            {

                if (item.ToString() == _FileSettings.FileSeparator) 
                {
                    cmbSeparator.SelectedIndex = tmpNum;
                }
                tmpNum++;
            }
            tmpNum = 0;
            foreach (var item in cmbCode.Items)
            {

                if (item.ToString() == _FileSettings.FileSeparator)
                {
                    cmbCode.SelectedIndex = tmpNum;
                }
                tmpNum++;
            }

            bool tmp_chFC = true; bool tmp_chKov = true;
            if (bool.TryParse(_FileSettings.File_chFC, out tmp_chFC)) chFC.Checked = tmp_chFC;
            if (bool.TryParse(_FileSettings.File_chKov, out tmp_chKov)) chKov.Checked = tmp_chKov;
        }


        ToolTip t = new ToolTip();
        t.SetToolTip(btnOpen, "Выбрать директорию файла");
        t.SetToolTip(btnLoad, "Загрузить файл для предварительного просмотра и выбора полей для чистки");
        t.SetToolTip(btnClean, "Прочистить выбранные поля с помощью сервисов IQDQ");



        
     }

    public void grdColumn_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        aejw.cIni oIni = null;

        oIni = new aejw.cIni(frmClean.cCfg.AppPath + "\\settings.ini");
      
        
        string Item;
        
        if (grdColumn.CurrentCell != null)
        {
           
    
            frmClean.cCfg.StartUpdateCol = grdColumn.RowCount + 3;
            Item = grdColumn.CurrentCell.Value.ToString();
            Color DeffColor = ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor;
            
            switch (Item)
            {
   
                case "Не обрабатывать":
                    frmClean.cCfg.Ind = grdColumn.CurrentCell.OwningRow.Index + 2;
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = false;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item);                   
                    ((DataGridViewRow)grdColumn.Rows[e.RowIndex]).DefaultCellStyle.BackColor = Color.White;
                    oIni.WriteValue("CheckType", "NowCheck", ""); frmClean.cCfg.CheckType = "";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    choose_addrmatch = false;
                    break;
                case "Адрес (в одном поле)":                 
                    if (chFC.Checked)
                    {
                        frmClean.cCfg.Ind = grdColumn.CurrentCell.OwningRow.Index + 2;
                        frmClean.cCfg.StartInd = grdColumn.CurrentCell.OwningRow.Index + 2;
                        grdColumn.CurrentRow.Cells["IsAddr"].Value= true;
                        oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item);
                        oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                        
                    }
                    else
                    {
                        frmClean.cCfg.Ind = grdColumn.CurrentCell.OwningRow.Index + 2;
                        grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                        oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item);
                        oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    }

                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
   
                    frmClean.cCfg.AddrFullAddressCompareIndex += 1;  ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen; break;
                /*case "Тип Адреса":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    frmClean.cCfg.StartUpdateCol = grdColumn.RowCount + 3;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";                  

                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break;
                case "Страна":                   
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    frmClean.cCfg.StartUpdateCol = grdColumn.RowCount + 4;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item);
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen; 
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "Тип региона":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen; 
                    AddrMatch = true;
                    EmailMatch = false;
                    OrgDublMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "Регион":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen; 
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "Тип района":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    OrgDublMatch = false;
                    FioMatch_2 = false;
                    break; 
                case "Район":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    OrgDublMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "Тип города":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "Город":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Тип НП":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "НП":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Тип улицы":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Улица":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Тип дома":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Дом":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    OrgDublMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "Корпус":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    OrgDublMatch = false;
                    FioMatch_2 = false;
                    break; 
                case "Строение":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    OrgDublMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    break; 
                case "Литера":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    OrgDublMatch = false;
                    FioMatch_2 = false;
                    break;                
                case "Тип квартиры":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Квартира":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Индекс":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "КЛАДР":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break;
                   
                case "ОКАТО":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "ОКТМО":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                case "Дом с квартирой":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "addrmatch"); frmClean.cCfg.CheckType = "addrmatch";
                    AddrMatch = true;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; */
                case "E-mail":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;                
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "emailmatch"); frmClean.cCfg.CheckType = "emailmatch";
                    AddrMatch = false;
                    EmailMatch = true;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break; 
                /*case "ФИО (в одном поле)":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    //grdColumn.CurrentRow.Cells["IsAddr"].OwningColumn.HeaderText = "Это " + Item;;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "fiomatch_1"); frmClean.cCfg.CheckType = "fiomatch_1";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = true;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break;
                case "Отчество":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    //grdColumn.CurrentRow.Cells["IsAddr"].OwningColumn.HeaderText = "Это " + Item;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2"); frmClean.cCfg.CheckType = "fiomatch_2";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = true;
                    OrgDublMatch = false;
                    break;
                
                case "Имя":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    //grdColumn.CurrentRow.Cells["IsAddr"].OwningColumn.HeaderText = "Это " + Item;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;  
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen; 
                     oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2"); frmClean.cCfg.CheckType = "fiomatch_2";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = true;
                    OrgDublMatch = false;
                    break;
                case "Фамилия":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    //grdColumn.CurrentRow.Cells["IsAddr"].OwningColumn.HeaderText = "Это " + Item;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2"); frmClean.cCfg.CheckType = "fiomatch_2";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = true;
                    OrgDublMatch = false;
                    break; 

                case "Телефон":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    //grdColumn.CurrentRow.Cells["IsAddr"].OwningColumn.HeaderText = "Это " + Item;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                     oIni.WriteValue("CheckType", "NowCheck", "phonematch"); frmClean.cCfg.CheckType = "phonematch";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = true;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    break;
                case "Организация":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    //grdColumn.CurrentRow.Cells["IsAddr"].OwningColumn.HeaderText = "Это " + Item;

                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item); frmClean.cCfg.AddrFullAddressCompareIndex += 1;
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "orgdublmatch"); frmClean.cCfg.CheckType = "orgdublmatch";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = true;
                    break;

                case "Адрес (Для выбора)":
                    grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
                    //grdColumn.CurrentRow.Cells["IsAddr"].OwningColumn.HeaderText = "Это " + Item;
                    frmClean.cCfg.Ind = grdColumn.CurrentCell.OwningRow.Index + 2;
                    oIni.WriteValue("LoadedCollumns", grdColumn.CurrentRow.Cells[0].Value.ToString(), Item);
                    frmClean.cCfg.AddrFullAddressCompareIndex += 1;
                    ((DataGridViewRow)grdColumn.CurrentCell.OwningRow).DefaultCellStyle.BackColor = Color.LightGreen;
                    oIni.WriteValue("CheckType", "NowCheck", "choose_addrmatch"); 
                    frmClean.cCfg.CheckType = "choose_addrmatch";
                    AddrMatch = false;
                    EmailMatch = false;
                    PhoneMatch = false;
                    FioMatch_1 = false;
                    FioMatch_2 = false;
                    OrgDublMatch = false;
                    choose_addrmatch = true;

                    break;*/
                

            }
        }
    }

    private void grdColumn_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void grdColumn_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        
    }

    private void grdColumn_CurrentCellChanged(object sender, EventArgs e)
    {
        
    }

    private void grdColumn_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        if (((DataGridView)sender).IsCurrentCellDirty) ((DataGridView)sender).CommitEdit(DataGridViewDataErrorContexts.Commit);       
    }

    private void grdColumn_CellClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void cmbTbl_SelectedIndexChanged(object sender, EventArgs e)
    {
       
    }

    private void pr_Grid1_Load(object sender, EventArgs e)
    {

    }

    private void edFile_TextChanged(object sender, EventArgs e)
    {
        frmClean.cCfg.LastFilePath = edFile.Text;
       
    }

    private void cmbTbl_TextChanged(object sender, EventArgs e)
    {
        int stop = 1;

       

        if (cmbTbl.SelectedValue != null)
        {
            ((frmMine)this.Owner).cfg.CleanFileName = cmbTbl.Text;
            ABDLight.Properties.Settings.Default.CleanFileName = ((frmMine)this.Owner).cfg.CleanFileName;
            ABDLight.Properties.Settings.Default.Save();
        }

        if (cmbTbl.Text.IndexOf(".") > 0)
        {
            frmClean.cCfg.LastFileName = cmbTbl.Text;
            ((frmMine)this.Owner).cfg.CleanFileName = cmbTbl.Text;
            ABDLight.Properties.Settings.Default.CleanFileName = ((frmMine)this.Owner).cfg.CleanFileName;
            ABDLight.Properties.Settings.Default.Save();
        }
    }

    private void cmbTbl_SelectedValueChanged(object sender, EventArgs e)
    {

    }

    private void frmLoad_FormClosing(object sender, FormClosingEventArgs e)
    {
        
        
    }

    private void frmLoad_FormClosed(object sender, FormClosedEventArgs e)
    {
        
        
         
    }

    private void grdColumn_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {          

    }

    private void btnLoad_MouseClick(object sender, MouseEventArgs e)
    {
        
    }

    private void cmbCode_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void chFC_CheckedChanged(object sender, EventArgs e)
    {

    }

//    public string ExecuteCommand(string name, Hashtable _pars = null)
//    {
//        // создаем прогресс
//        frmProgress frm = new frmProgress();
//        frm.Owner = Program.applicationContext.MainForm;
//        // передаем параметры в Tag формы прогресса
//        if (_pars == null)
//        {
//            _pars = new Hashtable();
//        }
        
//        _pars.Add("name", name);

//        frm.Tag = _pars;


//        // запускаем процесс выполнения запроса в отдельном потоке
//        Thread t = new Thread(ExecuteCommandThread);
//        t.IsBackground = true;
//        t.Start(frm);

//        // показываем прогесс
//        frm.ShowDialog();

//        // возвращаем результат из Tag формы прогресса
//        return (string)frm.Tag;
//    }
//    private void ExecuteCommandThread(object args)
//    {
//        frmProgress frm = (frmProgress)args;
//        string name = ((Hashtable)frm.Tag)["name"].ToString();

//        frm.SetDescription(String.Format("Выполняю команду {0}", name));

     

//        string result = "";


//        if (name == "Clean")
//        {
//            TreadClean();
//        }

//        if(name == "OpenTextFileToDB")
//        {
//            string isPreview = ((Hashtable)frm.Tag)["isPreview"].ToString();
//            int tmpMaxRowsToRead = 100;

//            if (isPreview.ToLower() == "true")
//            {
//                tmpMaxRowsToRead = 100;
               
//            }
//            else if (isPreview.ToLower() == "false")
//            {
               
//                int.TryParse(ABDLight.Properties.Settings.Default.MaxRowsToRead, out tmpMaxRowsToRead);
//            }

//            bool _isCreate = false;
//            string isCreate = ((Hashtable)frm.Tag)["isCreate"].ToString();
//            bool.TryParse(isCreate, out _isCreate);


//            DataTable DTtemp = new DataTable();

//            string _edFile = "";
//            edFile.Invoke((MethodInvoker)delegate
//            {
//                _edFile = edFile.Text;
//            });
//            string _cmbTbl = "";
//            cmbTbl.Invoke((MethodInvoker)delegate
//            {
//                _cmbTbl = cmbTbl.Text;
//            });
//            string _cmbCode = "";
//            cmbCode.Invoke((MethodInvoker)delegate
//            {
//                _cmbCode = cmbCode.Text;
//            });
//            string _cmbSeparator = "";
//            cmbSeparator.Invoke((MethodInvoker)delegate
//            {
//                _cmbSeparator = cmbSeparator.Text;
//            });
//            bool _chFC = true;
//            chFC.Invoke((MethodInvoker)delegate
//            {
//                _chFC = chFC.Checked;
//            });
//            bool _chKov = true;
//            chKov.Invoke((MethodInvoker)delegate
//            {
//                _chKov = chKov.Checked;
//            });
//            int SelInd = 0;
//            cmbType.Invoke((MethodInvoker)delegate
//            {
//                SelInd = cmbType.SelectedIndex;
//            });

//            if (SelInd == 1)
//                ((frmMine)this.Owner).dtMain = ExcelFunctions.ReadFile(_edFile, _cmbTbl, _chFC, "XLS", tmpMaxRowsToRead-1);
//            if (SelInd == 2)
//                ((frmMine)this.Owner).dtMain = ExcelFunctions.ReadFile(_edFile, _cmbTbl, _chFC, "XLSX", tmpMaxRowsToRead-1);
//            if (SelInd == 0)
//            CleanBackUp.readCSVandSave2DB(_edFile + "/" + _cmbTbl, DTtemp, _cmbCode, _cmbSeparator, _chFC, _chKov, tmpMaxRowsToRead-1, _isCreate);
//            //CleanBackUp.OpenTextFileToDB(_edFile + "/" + _cmbTbl, DTtemp, _cmbCode, _cmbSeparator, _chFC, _chKov, tmpMaxRowsToRead);
           
//           // ((frmMine)this.Owner).dtMain = CleanBackUp.GetDataTable(ABDLight.Properties.Settings.Default.ABDLightDBConnectionString, ABDLight.Properties.Settings.Default.DB, ABDLight.Properties.Settings.Default.Table);
//        }else 
//        if(name == "OpenFromDB")
//        {
//            aejw.cIni oIni = null;
//            oIni = new aejw.cIni(frmClean.cCfg.AppPath + "\\settings.ini");


//            string DB_Name = ""; 
//            if (((Hashtable)frm.Tag)["DB_Name"] != null)
//            {
//                DB_Name = ((Hashtable)frm.Tag)["DB_Name"].ToString(); 
//                if (string.IsNullOrEmpty(DB_Name))
//                {
//                    DB_Name = ABDLight.Properties.Settings.Default.Table;
//                }
//            }
//            else if (((Hashtable)frm.Tag)["DB_Name"] == null)
//            {
//                DB_Name = ABDLight.Properties.Settings.Default.Table;
//            }

//            string _edFile = "";
//            edFile.Invoke((MethodInvoker)delegate
//            {
//                _edFile = edFile.Text;
//            });
//            string _cmbTbl = "";
//            cmbTbl.Invoke((MethodInvoker)delegate
//            {
//                _cmbTbl = cmbTbl.Text;
//            });
//            string _cmbCode = "";
//            cmbCode.Invoke((MethodInvoker)delegate
//            {
//                _cmbCode = cmbCode.Text;
//            });
//            string _cmbSeparator = "";
//            cmbSeparator.Invoke((MethodInvoker)delegate
//            {
//                _cmbSeparator = cmbSeparator.Text;
//            });
//            bool _chFC = true;
//            chFC.Invoke((MethodInvoker)delegate
//            {
//                _chFC = chFC.Checked;
//            });
//            bool _chKov = true;
//            chKov.Invoke((MethodInvoker)delegate
//            {
//                _chKov = chKov.Checked;
//            });



//            CleanBackUp.GetDataTable(ABDLight.Properties.Settings.Default.ABDLightDBConnectionString, ABDLight.Properties.Settings.Default.DB, ABDLight.Properties.Settings.Default.Table, "", ((frmMine)this.Owner).dtMain);

            
//            if(((frmMine)this.Owner).dtMain.Columns["ID_IQ"] == null)
//            {
//                DataColumn ID_IQ = new DataColumn();
//                ID_IQ.ColumnName = "ID_IQ";
//                ID_IQ.DataType = System.Type.GetType("System.Int32");
//                ((frmMine)this.Owner).dtMain.Columns.Add(ID_IQ);

//                ID_IQ.SetOrdinal(0);
//            }



//            if (((frmMine)this.Owner).dtMain.Columns["ID_IQ"] != null)
//            {
//                for (Int32 ind = 0; ind < ((frmMine)this.Owner).dtMain.Rows.Count; ind++)
//                {
//                    ((frmMine)this.Owner).dtMain.Rows[ind]["ID_IQ"] = ind + 1;
//                }
//            }
////
            
                
//                pr_Grid1.LoadGrig(((frmMine)this.Owner).dtMain);
               
//                for (int i = 1; i < ((frmMine)this.Owner).dtMain.Columns.Count; i += 1)
//                {
                    
//                    grdColumn.Invoke((MethodInvoker)delegate
//                    {
//                        grdColumn.Rows.Add(1);

//                        grdColumn.Rows[i - 1].Cells[0].Value = ((frmMine)this.Owner).dtMain.Columns[i].ColumnName;

//                        string ColumnType = "Не обрабатывать";


//                        ColumnType = oIni.ReadValue("LoadedCollumns", ((frmMine)this.Owner).dtMain.Columns[i].ColumnName, ColumnType);
                        
//                        switch (ColumnType)
//                        {
//                            case "Не обрабатывать":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[0];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = false;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = false;
//                                ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.White;


//                                break;
//                            case "Адрес (в одном поле)":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[1];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true;
//                                ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                           /* case "Тип Адреса":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[2];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Страна":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[3];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Тип региона":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[4];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Регион":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[5];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Тип района":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[6];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Район":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[7];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Тип города":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[8];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Город":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[9];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Тип НП":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[10];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "НП":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[11];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Тип улицы":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[12];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Улица":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[13];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Тип дома":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[14];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Дом":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[15];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Корпус":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[16];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Строение":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[17];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Литера":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[18];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Тип квартиры":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[19];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Квартира":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[20];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "Индекс":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[21];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "addrmatch");
//                                frmClean.cCfg.CheckType = "addrmatch";
//                                break;
//                            case "КЛАДР":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[22];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break;
//                            case "ОКАТО":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[23];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break;
//                            case "ОКТМО":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[24];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break;
//                            case "Дом с квартирой":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[25];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen; break;*/
//                            case "E-mail":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[2];
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "emailmatch");
//                                frmClean.cCfg.CheckType = "emailmatch";
//                                break;
//                            /*case "ФИО (в одном поле)":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[27];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "fiomatch_1");
//                                frmClean.cCfg.CheckType = "fiomatch_1";
//                                break;
//                            case "Отчество":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[28];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2");
//                                frmClean.cCfg.CheckType = "fiomatch_2";
//                                break;
//                            case "Имя":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[29];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2");
//                                frmClean.cCfg.CheckType = "fiomatch_2";
//                                break;
//                            case "Фамилия":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[30];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "fiomatch_2");
//                                frmClean.cCfg.CheckType = "fiomatch_2";
//                                break;
//                            case "Телефон":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[31];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "phonematch");
//                                frmClean.cCfg.CheckType = "phonematch";
//                                break;
//                            case "Организация":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[32];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "orgdublmatch");
//                                frmClean.cCfg.CheckType = "orgdublmatch";
//                                break;
//                            case "Адрес (Для выбора)":
//                                grdColumn.Rows[i - 1].Cells[2].Value = inputType_Name.Items[33];
//                                grdColumn.CurrentRow.Cells["IsAddr"].Value = true;
//                                grdColumn.Rows[i - 1].Cells["IsAddr"].Value = true; ((DataGridViewRow)grdColumn.Rows[i - 1]).DefaultCellStyle.BackColor = Color.LightGreen;
//                                oIni.WriteValue("CheckType", "NowCheck", "choose_addrmatch");
//                                frmClean.cCfg.CheckType = "choose_addrmatch";
//                                break;*/

//                        }
                          
//                    });

                  
//                }
                
//                   lbCount.Text = "Всего загружено: " + ((frmMine)this.Owner).dtMain.Rows.Count.ToString() + " записей";
            
     
    
//            //CleanBackUp.OpenTextFileToDB(_edFile + "/" + _cmbTbl, DTtemp, _cmbCode, _cmbSeparator, _chFC, _chKov, tmpMaxRowsToRead);

            
//        }
//        //result.Load(String.Format("https://api.vkontakte.ru/method/{0}.xml?access_token={1}&{2}", name, this.AccessToken, String.Join("&", from item in qs.AllKeys select item + "=" + qs[item])));

//        frm.SetDescription("Команда успешно выполнена.");

//        // передаем результат в Tag формы прогресса
//        frm.SetTag(result);
//        // закрываем форму прогресса
//        frm.CloseMe();
//    }

    private void button_LoadFromDB_Click(object sender, EventArgs e)
    {

        string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
        SQLiteData.DBCreate();
        SQLiteData.CreateTable(((frmMine)this.Owner).dtMain, TabName);
        SQLiteData.InsertTable(((frmMine)this.Owner).dtMain, TabName);

        //Запуск подсчета времени выполнения
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();



        var tasks = new List<Task>();
        //var numberCores = 12;//Environment.ProcessorCount;
        var numberCores = Convert.ToInt32(textBox1.Text.ToString());
        int count = SQLiteData.GetRecordCount(ABDLight.Properties.Settings.Default.CleanFileName);
        double dstep = Convert.ToDouble(count) / numberCores;
        int step = Convert.ToInt16(Math.Ceiling(dstep));

        for (int i = 0; i < numberCores; i++)
        {
            int start, end;
            start = i * step + 1;
            if (i * step + step <= count)
                end = i * step + step;
            else
                end = count;

            var addr = new List<string>();

            //for (int j = start; j < end; j++)
             //   addr.Add(SQLiteData.GetAddrByID(ABDLight.Properties.Settings.Default.CleanFileName, j, sql_con_thread));


            var task = new Task(() => DoSomeLongWork2(addr), TaskCreationOptions.LongRunning);
            task.Start();
            //var task = Task.Factory.StartNew(DoSomeLongWork, TaskCreationOptions.LongRunning);
            tasks.Add(task);
        }

        Task.WaitAll(tasks.ToArray());

        // Останавливаем таймер 
        stopWatch.Stop();
        TimeSpan ts = stopWatch.Elapsed;

        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds);

        MessageBox.Show(elapsedTime, "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Error);



    }

    void DoSomeLongWork2(List<string> addrlist)
    {
        string addr2;
        string conn;
        string res;

        foreach (string addr in addrlist)
        {
            conn = "http://iqdq.ru/Services/IQDQ/SearchAddressDetail?addr=" + addr + "&login=admin&pwd=RgH75bmLTg";
            res = new StreamReader(HttpWebRequest.Create(conn).GetResponse().GetResponseStream()).ReadToEnd();
            addr2 = res;

        }

    }








    private void gbTop_Enter(object sender, EventArgs e)
    {

    }

        public class CleanInfo
        {
            public string CleanFileName {get;set;}
            public string FileName {get;set;}
            public Paramm _Paramm { get; set; }
            public CleanInfo()
            {
                CleanFileName = "";
                FileName = "";
                _Paramm = new Paramm();
            }
          
        }
            public class Paramm
            {
                public string NumberCores { get; set; }
                public string Count { get; set; }

                public Paramm()
                {
                    NumberCores = "";
                    Count = "";
                }
            }
    

        
    public void TreadClean()
    {
        //Запуск подсчета времени выполнения
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        //var tasks = new List<Task>();
        //Количество создаваемых задач
        
        //var tasks = new List<Task>();
        //var numberCores = Environment.ProcessorCount;

        //Thread[] trArr = new Thread[numberCores];
        //int[] ArrInt = new int[2];

        //int count = SQLiteData.GetRowCount(ABDLight.Properties.Settings.Default.CleanFileName);
        //double dstep = Convert.ToDouble(count) / numberCores;
        //int step = Convert.ToInt16(Math.Ceiling(dstep));

        //for (int i = 0; i < numberCores; i++)
        //{
        //    var addr = new List<string>();

        //    for (int j = i * step + 1; j < i * step + step; j++)
        //        addr.Add(SQLiteData.GetAddrByID(ABDLight.Properties.Settings.Default.CleanFileName, j));

        //    ArrInt[0] = i * step + 1;
        //    if (i * step + step <= count)
        //        ArrInt[1] = i * step + step;
        //    else
        //        ArrInt[1] = count;

        //    trArr[i] = new Thread(new ParameterizedThreadStart(DoSomeLongWork));
        //    trArr[i].Start(ArrInt);
        //    //trArr[i].Start(addr);

        //}

        ////ждём завершения всех потоков
        //for (int i = 0; i < numberCores; i++)
        //{
        //    trArr[i].Join();
        //}
  
        
        var tasks = new List<Task>();
        //var numberCores = 12;//Environment.ProcessorCount;
        var numberCores = Convert.ToInt32(textBox1.Text.ToString());
        int count = SQLiteData.GetRecordCount(ABDLight.Properties.Settings.Default.CleanFileName) + 1;
        double dstep = Convert.ToDouble(count) / numberCores;
        int step = Convert.ToInt16(Math.Ceiling(dstep));

        string databaseName = ABDLight.Properties.Settings.Default.SQLiteDB;
        string.Format("Data Source={0};", databaseName);
        DataTable dt = CleanBackUp.GetDataTable_SQLite(string.Format("Data Source={0};", databaseName), "ABDLightDB", ABDLight.Properties.Settings.Default.CleanFileName);

       
  


        CleanInfo _CleanInfo = new CleanInfo();
        _CleanInfo.CleanFileName = ABDLight.Properties.Settings.Default.CleanFileName;
        _CleanInfo.FileName = ABDLight.Properties.Settings.Default.CleanFileName;
        _CleanInfo._Paramm.Count = count.ToString();
        _CleanInfo._Paramm.NumberCores = numberCores.ToString();


        string json = JsonConvert.SerializeObject(_CleanInfo);

        string ColumnWhithAddress = "";
        int ii = 0;
        DataGridView rows = grdColumn;


        try
        {
            while (ii != rows.RowCount)
            {

                if (rows["IsAddr", ii].Value.ToString().ToLower() == "true")
                {
                    ColumnWhithAddress = rows[0, ii].Value.ToString();

                }
                ii++;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Ошибка при выполнении!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
     


        try
        {
            for (int i = 0; i < numberCores; i++)
            {
                int start, end;
                start = i * step + 1;
                if (i * step + step <= count)
                    end = i * step + step;
                else
                    end = count;

                var addr = new List<string>();

                try
                {
                    for (int j = start; j < end; j++)
                    {

                        addr.Add(dt.Rows[j][ColumnWhithAddress].ToString());
                    }
                }
                catch
                {

                }
                var task = new Task(() => DoSomeLongWork(addr, start, json), TaskCreationOptions.LongRunning);
                task.Start();
                tasks.Add(task);
            }

            Task.WaitAll(tasks.ToArray());

            // Останавливаем таймер 
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds);

            MessageBox.Show(elapsedTime, "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch(Exception ex)
        {
          //  MessageBox.Show(ex.Message, "Ошибка при выполнении!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            foreach (KeyValuePair<string, string> item in CleanResult)
            {
                Dictionary<string, string> ress = JSONObject.ParseAllJSON(item.Value);

                foreach (KeyValuePair<string, string> itemRes in ress)
                {
                    string field = itemRes.Key.Substring(0, itemRes.Key.IndexOf("_#_"));
                    if ("c_address_full" == field)
                    {
                        Console.Write("{0},{1},{2}", item.Key, ". Разобранный адрес:  ", itemRes.Value);
                    }
                    if ("c_house_str" == field)
                    {
                        Console.Write("{0},{1},{2}", " ", itemRes.Value, "\r\n");
                    }
                    //Console.Write("{0},{1},{2}", itemRes.Key.Substring(0, itemRes.Key.IndexOf("_#_")), itemRes.Value, " || ");
                }
            }
        
        }
      

    }
    //непосредственно DoSomeLongWork - то что мы выполняем
    void DoSomeLongWork(List<string> addrlist, int start, string CleanInfo = "")
    {
        //Thread.Sleep(1000);
        //string addr;
        string addr2;
        string conn;
        string res;

       // int[] bArr = (int[])o;
        //int start = bArr[0];
        //int end = bArr[1];

        //for (int i = start; i < end; i++)
        //{
        //    //addr = ((frmMine)this.Owner).dtMain.Rows[i][1].ToString();
        //    addr = SQLiteData.GetAddrByID(ABDLight.Properties.Settings.Default.CleanFileName, i);
        //    conn = "http://iqdq.ru/Services/IQDQ/SearchAddressDetail?addr=" + addr + "&login=admin&pwd=RgH75bmLTg";
        //    res = new StreamReader(HttpWebRequest.Create(conn).GetResponse().GetResponseStream()).ReadToEnd();
        //    addr = res;
        //}
        


    
        foreach (string addr in addrlist)
        {
            //conn = ABDLight.Properties.Settings.Default.Http + "/Services/IQDQ/SearchAddressDetail?addr=" + addr + "&login=" + ABDLight.Properties.Settings.Default.Login + "&pwd=" + ABDLight.Properties.Settings.Default.edPwd;
            conn = "http://www.iqdq.ru/Services/IQDQ/SearchAddressDetail?addr=" + addr + "&login=" + ABDLight.Properties.Settings.Default.Login + "&pwd=" + ABDLight.Properties.Settings.Default.edPwd;
            res = new StreamReader(HttpWebRequest.Create(conn).GetResponse().GetResponseStream()).ReadToEnd();
            CleanResult.Add(start.ToString(), res);     
           // CleanResultDT.Rows.Add(start.ToString(), res, CleanInfo);
            start++;
            /*
            Dictionary<string, string> ress = JSONObject.ParseAllJSON(res);
            foreach (KeyValuePair<string, string> item in ress)
            {
                Console.Write ("{0},{1},{2}",item.Key.Substring(0, item.Key.IndexOf("_#_")), item.Value, " || "  );
                
            }
            Console.WriteLine();
             * */
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {


       // btnLoad_Click(null, null);

       // FileInfo file = null;
       // if (cmbType.SelectedIndex <= 1)
       // {
       //     file = new FileInfo(((frmLoad)this).edFile.Text + "\\" + cmbTbl.SelectedItem.ToString());
       // }
       // else
       // {
       //     file = new FileInfo(((frmLoad)this).edFile.Text);
       // }
       // ABDLight.Properties.Settings.Default.CleanFileName = file.Name;
       // ABDLight.Properties.Settings.Default.Save();

       // /*
       // if (CleanResultDT == null) { CleanResultDT = new DataTable(file.Name.Replace(file.Extension, "") + "_clean" + file.Extension); }

       // CleanResultDT.Columns.Clear();

       // DataColumn iqid = new DataColumn();
       // iqid.ColumnName = "iqid";
       // iqid.Caption = "iqid";
       // iqid.DataType = System.Type.GetType("System.String");

       // CleanResultDT.Columns.Add(iqid);

       // DataColumn result = new DataColumn();
       // result.ColumnName = "result";
       // result.Caption = "result";
       // result.DataType = System.Type.GetType("System.String");

       // CleanResultDT.Columns.Add(result);

       // DataColumn CleanInfo = new DataColumn();
       // CleanInfo.ColumnName = "CleanInfo";
       // CleanInfo.Caption = "CleanInfo";
       // CleanInfo.DataType = System.Type.GetType("System.String");

       // CleanResultDT.Columns.Add(CleanInfo);
       // */
       // string TabName = ABDLight.Properties.Settings.Default.CleanFileName;
       // SQLiteData.DBCreate();
       // SQLiteData.CreateTable(((frmMine)this.Owner).dtMain, TabName);
       // SQLiteData.InsertTable(((frmMine)this.Owner).dtMain, TabName);

       // Hashtable pars = new Hashtable();
       // pars.Add("Execute", "TreadClean");
       // ExecuteCommand("Clean", pars);

       //// TreadClean();
    }

    public void OpenTextFileToDB(frmProgress frm)
    {
        string isPreview = ((Hashtable)frm.Tag)["isPreview"].ToString();
        int tmpMaxRowsToRead = 100;

        if (isPreview.ToLower() == "true")
        {
            tmpMaxRowsToRead = 100;
               
        }
        else if (isPreview.ToLower() == "false")
        {
               
            int.TryParse(ABDLight.Properties.Settings.Default.MaxRowsToRead, out tmpMaxRowsToRead);
        }

        bool _isCreate = false;
        string isCreate = ((Hashtable)frm.Tag)["isCreate"].ToString();
        bool.TryParse(isCreate, out _isCreate);


        DataTable DTtemp = new DataTable();

        string _edFile = "";
        edFile.Invoke((MethodInvoker)delegate
        {
            _edFile = edFile.Text;
        });
        string _cmbTbl = "";
        cmbTbl.Invoke((MethodInvoker)delegate
        {
            _cmbTbl = cmbTbl.Text;
        });
        string _cmbCode = "";
        cmbCode.Invoke((MethodInvoker)delegate
        {
            _cmbCode = cmbCode.Text;
        });
        string _cmbSeparator = "";
        cmbSeparator.Invoke((MethodInvoker)delegate
        {
            _cmbSeparator = cmbSeparator.Text;
        });
        bool _chFC = true;
        chFC.Invoke((MethodInvoker)delegate
        {
            _chFC = chFC.Checked;
        });
        bool _chKov = true;
        chKov.Invoke((MethodInvoker)delegate
        {
            _chKov = chKov.Checked;
        });
        int SelInd = 0;
        cmbType.Invoke((MethodInvoker)delegate
        {
            SelInd = cmbType.SelectedIndex;
        });

        if (SelInd == 1)
            ((frmMine)this.Owner).dtMain = ExcelFunctions.ReadFile(_edFile, _cmbTbl, _chFC, "XLS", tmpMaxRowsToRead-1);
        if (SelInd == 2)
            ((frmMine)this.Owner).dtMain = ExcelFunctions.ReadFile(_edFile, _cmbTbl, _chFC, "XLSX", tmpMaxRowsToRead-1);
        if (SelInd == 0)
            CleanBackUp.readCSVandSave2DB(_edFile + "/" + _cmbTbl, DTtemp, _cmbCode, _cmbSeparator, _chFC, _chKov, tmpMaxRowsToRead-1, _isCreate);
    }
    

  }

}
